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
1 +//
2 +// WarplyEvents.h
3 +// App
4 +//
5 +// Created by Fotios Kalaitzidis on 23/10/2018.
6 +// Copyright © 2018 Facebook. All rights reserved.
7 +//
8 +#import <Foundation/Foundation.h>
9 +
10 +@interface WarplyReactMethods : NSObject
11 +
12 +@end
1 +//
2 +// WarplyEvents.m
3 +// App
4 +//
5 +// Created by Fotios Kalaitzidis on 23/10/2018.
6 +// Copyright © 2018 Facebook. All rights reserved.
7 +//
8 +
9 +#import "WarplyReactMethods.h"
10 +#import "WLUserManager.h"
11 +#import "WLAnalyticsManager.h"
12 +#import "Warply.h"
13 +#import <AdSupport/AdSupport.h>
14 +
15 +@implementation WarplyReactMethods
16 +- (void) sendEvent: (NSString *) eventName priority: (BOOL) priority {
17 + NSString *event_Name = eventName;
18 + NSNumber *time_submitted = [NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]];
19 + NSDictionary *inapp_event = [NSDictionary dictionaryWithObjectsAndKeys:event_Name, @"event_id", nil, @"page_id", time_submitted, @"time_submitted", nil, @"action_metadata", nil];
20 + NSDictionary *eventContext = [NSDictionary dictionaryWithObject:inapp_event forKey:@"inapp_analytics"];
21 + WLEventSimple *simpleEvent = [[WLEventSimple alloc] initWithType:@"inapp_analytics" andContext:eventContext];
22 +
23 + [[Warply sharedService] addEvent:simpleEvent priority:priority];
24 +}
25 +
26 +- (NSString *) getUniqueId {
27 + return [[[UIDevice currentDevice] identifierForVendor] UUIDString];
28 +}
29 +
30 +
31 +- (NSString *) getAdvertisementId {
32 + return [[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString];
33 +}
34 +
35 +
36 +@end
1 +MIT License
2 +Copyright © 2018 Matan Cohen
3 +Permission is hereby granted, free of charge, to any person obtaining a copy
4 +of this software and associated documentation files (the "Software"), to deal
5 +in the Software without restriction, including without limitation the rights
6 +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 +copies of the Software, and to permit persons to whom the Software is
8 +furnished to do so, subject to the following conditions:
9 +The above copyright notice and this permission notice shall be included in all
10 +copies or substantial portions of the Software.
11 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
12 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
13 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
14 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
15 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
16 +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
17 +SOFTWARE.
...\ No newline at end of file ...\ No newline at end of file
1 +{
2 + "info" : {
3 + "author" : "xcode",
4 + "version" : 1
5 + }
6 +}
1 +{
2 + "images" : [
3 + {
4 + "filename" : "logo.png",
5 + "idiom" : "universal",
6 + "scale" : "1x"
7 + },
8 + {
9 + "filename" : "logo-1.png",
10 + "idiom" : "universal",
11 + "scale" : "2x"
12 + },
13 + {
14 + "filename" : "logo-2.png",
15 + "idiom" : "universal",
16 + "scale" : "3x"
17 + }
18 + ],
19 + "info" : {
20 + "author" : "xcode",
21 + "version" : 1
22 + }
23 +}
No preview for this file type
1 +/*
2 + Copyright 2010-2016 Warply Inc. All rights reserved.
3 +
4 + Redistribution and use in source and binary forms, without modification,
5 + are permitted provided that the following conditions are met:
6 +
7 + 1. Redistributions of source code must retain the above copyright notice, this
8 + list of conditions and the following disclaimer.
9 +
10 + 2. Redistributions in binaryform must reproduce the above copyright notice,
11 + this list of conditions and the following disclaimer in the documentation
12 + and/or other materials provided with the distribution.
13 +
14 + THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 + EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 + */
25 +
26 +/*!
27 + @header WLEvent.h
28 + The WLEvent provides a functional interface for Warply events.
29 + Use the methods declared here to initialise and create events with arbitrary
30 + context and type.
31 + @copyright Warply Inc.
32 + */
33 +#import <Foundation/Foundation.h>
34 +
35 +/*!
36 + @class WLEvent
37 + @discussion This class provides methods for creating an event with arbitrary
38 + context.
39 + */
40 +@interface WLEvent : NSObject
41 +{
42 +@protected
43 + NSString *_time;
44 + NSMutableDictionary *_data;
45 +}
46 +
47 +/*!
48 + @methodgroup Class Methods
49 + @discussion Convinience class methods for initialising an event.
50 + */
51 +/*!
52 + @abstract Creates an event.
53 + @discussion Initializes and returns a newly allocated WLEvent object.
54 + Initializes and returns a newly allocated WLEvent object.
55 + @return Returns WLEvent object.
56 + */
57 ++ (id)event;
58 +/*!
59 + @abstract Creates an event with arbitrary context.
60 + @discussion Initializes and returns a newly allocated WLEvent object with the
61 + arbitrary context.
62 + @param context A dictionary object with arbitrary key-value entries.
63 + @return Returns WLEvent object.
64 + */
65 ++ (id)eventWithContext:(NSDictionary*)context;
66 +
67 +/*!
68 + @property time
69 + @abstract A string with event created time in epoch format. Read only property.
70 + */
71 +@property (nonatomic, readonly) NSString *time;
72 +/*!
73 + @property data
74 + @abstract A dictionary with event context. Read only property.
75 + */
76 +@property (nonatomic, readonly) NSMutableDictionary *data;
77 +
78 +/*!
79 + @methodgroup Initialising Event
80 + */
81 +/*!
82 + @abstract Initialise an WLevent object.
83 + @discussion Initializes and returns a newly allocated WLEvent object with the
84 + arbitrary context.
85 + @param context A dictionary object with arbitrary key-value entries.
86 + @return Returns WLEvent object.
87 + */
88 +- (id)initWithContext:(NSDictionary*)context;
89 +/*!
90 + @methodgroup Getting Event Type
91 + */
92 +/*!
93 + @abstract Get event type.
94 + @discussion This method returns the type of the event.
95 + @return Returns a string object with event type.
96 + */
97 +- (NSString *)getType;
98 +/*!
99 + @methodgroup Adding Context to Event
100 + */
101 +/*!
102 + @abstract Add context to event.
103 + @discussion This method adds a key-value pair to existing context of an event.
104 + @param value An id object with the value of the key.
105 + @param key A string object with the key of the value.
106 + */
107 +- (void)addDataWithValue:(id)value forKey:(NSString*)key;
108 +
109 +@end
110 +
111 +/*!
112 + @class WLEventSimple
113 + @discussion This class provides methods for creating an event with arbitrary
114 + context and type.
115 + */
116 +@interface WLEventSimple : WLEvent
117 +{
118 +@private
119 + NSString *_type;
120 +}
121 +
122 +/*!
123 + @methodgroup Class Methods
124 + @discussion Convinience class methods for initialising an event.
125 + */
126 +/*!
127 + @abstract Creates an event with arbitrary type.
128 + @discussion Initializes and returns a newly allocated WLEventSimple object
129 + with arbitrary type.
130 + @param aType A string object with the event type.
131 + @return Returns WLEvent object.
132 + */
133 ++ (id)eventWithType:(NSString*)aType;
134 +/*!
135 + @abstract Creates an event with arbitrary type and context.
136 + @discussion Initializes and returns a newly allocated WLEventSimple object
137 + with arbitrary type and context.
138 + @param aType A string object with the event type.
139 + @param context A dictionary with arbitrary context.
140 + @return Returns WLEvent object.
141 + */
142 ++ (id)eventWithType:(NSString*)aType andContext:(NSDictionary*)context;
143 +
144 +/*!
145 + @methodgroup Initialising Event
146 + */
147 +/*!
148 + @abstract Initialise an event with arbitrary type.
149 + @discussion Initializes and returns a newly allocated WLEvent object with the
150 + arbitrary type.
151 + @param aType A string object with the event type.
152 + @return Returns WLEvent object.
153 + */
154 +- (id)initWithType:(NSString*)aType;
155 +/*!
156 + @abstract Initialise an event with arbitrary type and context.
157 + @discussion Initializes and returns a newly allocated WLEvent object with the
158 + arbitrary type and context.
159 + @param aType A string object with the event type.
160 + @param context A dictionary with arbitrary context.
161 + @return Returns WLEvent object.
162 + */
163 +- (id)initWithType:(NSString*)aType andContext:(NSDictionary*)context;
164 +
165 +@end
1 +/*
2 + Copyright 2010-2016 Warply Inc. All rights reserved.
3 +
4 + Redistribution and use in source and binary forms, without modification,
5 + are permitted provided that the following conditions are met:
6 +
7 + 1. Redistributions of source code must retain the above copyright notice, this
8 + list of conditions and the following disclaimer.
9 +
10 + 2. Redistributions in binaryform must reproduce the above copyright notice,
11 + this list of conditions and the following disclaimer in the documentation
12 + and/or other materials provided with the distribution.
13 +
14 + THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 + EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 + */
25 +
26 +#import "WLEvent.h"
27 +#import "WLGlobals.h"
28 +
29 +@interface WLEvent()
30 +
31 +- (void)gatherIndividualData:(NSDictionary*)context;
32 +- (void)gatherData:(NSDictionary*)context;
33 +
34 +@end
35 +
36 +@implementation WLEvent
37 +
38 +@synthesize time = _time;
39 +@synthesize data = _data;
40 +
41 +#pragma mark - Static Methods
42 +///////////////////////////////////////////////////////////////////////////////////////////////////
43 ++ (id)event
44 +{
45 +#if ! __has_feature(objc_arc)
46 + return [[[self alloc] init] autorelease];
47 +#else
48 + return [[self alloc] init];
49 +#endif
50 +}
51 +
52 +///////////////////////////////////////////////////////////////////////////////////////////////////
53 ++ (id)eventWithContext:(NSDictionary*)context
54 +{
55 +#if ! __has_feature(objc_arc)
56 + return [[[self alloc] initWithContext:context] autorelease];
57 +#else
58 + return [[self alloc] initWithContext:context];
59 +#endif
60 +}
61 +
62 +#pragma mark - Initialization
63 +///////////////////////////////////////////////////////////////////////////////////////////////////
64 +- (id)init
65 +{
66 + self = [super init];
67 + if (self) {
68 + _data = [NSMutableDictionary new];
69 + }
70 +
71 + return self;
72 +}
73 +
74 +///////////////////////////////////////////////////////////////////////////////////////////////////
75 +- (id)initWithContext:(NSDictionary*)context
76 +{
77 + self = [self init];
78 + if (self) {
79 + [self gatherData:context];
80 + }
81 +
82 + return self;
83 +}
84 +
85 +#pragma mark - Public Methods
86 +///////////////////////////////////////////////////////////////////////////////////////////////////
87 +- (NSString*)getType
88 +{
89 + return @"base";
90 +}
91 +
92 +///////////////////////////////////////////////////////////////////////////////////////////////////
93 +- (void)addDataWithValue:(id)value forKey:(NSString*)key
94 +{
95 + if (value && key)
96 + [_data setObject:value forKey:key];
97 +}
98 +
99 +#pragma mark - Private Methods
100 +///////////////////////////////////////////////////////////////////////////////////////////////////
101 +- (void)gatherIndividualData:(NSDictionary*)context { }
102 +
103 +///////////////////////////////////////////////////////////////////////////////////////////////////
104 +- (void)gatherData:(NSDictionary*)context {
105 + // in case we re-use a event object
106 + _time = [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970]];
107 + [_data removeAllObjects];
108 +
109 + // gather individual data
110 + [self gatherIndividualData:context];
111 +}
112 +
113 +@end
114 +
115 +///////////////////////////////////////////////////////////////////////////////////////////////////
116 +@implementation WLEventSimple
117 +
118 +#pragma mark - Static Methods
119 +///////////////////////////////////////////////////////////////////////////////////////////////////
120 ++ (id)eventWithType:(NSString*)aType
121 +{
122 + return [[self alloc] initWithType:aType];
123 +}
124 +
125 +///////////////////////////////////////////////////////////////////////////////////////////////////
126 ++ (id)eventWithType:(NSString*)aType andContext:(NSDictionary*)context
127 +{
128 + return [[self alloc] initWithType:aType andContext:context];
129 +}
130 +
131 +#pragma mark - Initialization
132 +///////////////////////////////////////////////////////////////////////////////////////////////////
133 +- (id)initWithType:(NSString*)aType
134 +{
135 + self=[super init];
136 + if (self) {
137 + _type = aType;
138 + }
139 + return self;
140 +}
141 +
142 +///////////////////////////////////////////////////////////////////////////////////////////////////
143 +- (id)initWithType:(NSString*)aType andContext:(NSDictionary*)context
144 +{
145 + self = [super initWithContext:context];
146 + if (self) {
147 + _type = aType;
148 + }
149 +
150 + return self;
151 +}
152 +
153 +#pragma mark - Public Methods
154 +///////////////////////////////////////////////////////////////////////////////////////////////////
155 +- (NSString*)getType
156 +{
157 + return _type;
158 +}
159 +
160 +#pragma mark - Override Methods
161 +///////////////////////////////////////////////////////////////////////////////////////////////////
162 +- (void)gatherIndividualData:(NSDictionary*)context
163 +{
164 + WLLOG(@"WLEvent Context: %@", context);
165 + [_data addEntriesFromDictionary:context];
166 +}
167 +
168 +@end
1 +/*
2 + Copyright 2010-2016 Warply Inc. All rights reserved.
3 +
4 + Redistribution and use in source and binary forms, without modification,
5 + are permitted provided that the following conditions are met:
6 +
7 + 1. Redistributions of source code must retain the above copyright notice, this
8 + list of conditions and the following disclaimer.
9 +
10 + 2. Redistributions in binaryform must reproduce the above copyright notice,
11 + this list of conditions and the following disclaimer in the documentation
12 + and/or other materials provided with the distribution.
13 +
14 + THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 + EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 + */
25 +
26 +///////////////////////////////////////////////////////////////////////////////
27 +// Base URL
28 +//#define WARP_PRODUCTION_BASE_URL @"https://engage-stage.warp.ly"
29 +//#define WARP_HOST @"engage-stage.warp.ly"
30 +//#define WARP_ERROR_DOMAIN @"engage-stage.warp.ly"
31 +extern NSString* WARP_PRODUCTION_BASE_URL;
32 +extern NSString* WARP_HOST;
33 +extern NSString* WARP_ERROR_DOMAIN;
34 +extern NSString* MERCHANT_ID;
35 +extern NSString* LANG;
36 +#define WARP_PAGE_URL_FORMAT @"%@/api/session/%@"
37 +#define WARP_IMAGE_URL_FORMAT @"%@/api/session/logo/%@"
38 +
39 +///////////////////////////////////////////////////////////////////////////////
40 +// Settings
41 +#ifdef _WL_VERSION
42 +#define WL_VERSION @ _WL_VERSION
43 +#else
44 +#define WL_VERSION @ "3.2.0a"
45 +#endif
46 +
47 +#define GEOFENCING_POIS_ENABLED @"GEOFENCING_POIS_ENABLED"
48 +#define WL_IOS_LOCATION_FOREGROUND_MODE @"IOS_LOCATION_FOREGROUND_MODE"
49 +#define WL_IOS_LOCATION_BACKGROUND_MODE @"IOS_LOCATION_BACKGROUND_MODE"
50 +#define WL_IOS_GEOFENCING_ENABLED @"IOS_GEOFENCING_ENABLED"
51 +#define WL_IOS_FOREGROUND_DISTANCE_FILTER @"IOS_FOREGROUND_DISTANCE_FILTER"
52 +#define WL_IOS_BACKGROUND_DISTANCE_FILTER @"IOS_BACKGROUND_DISTANCE_FILTER"
53 +#define WL_DEVICE_INFO_ENABLED @"DEVICE_INFO_ENABLED"
54 +#define WL_OFFERS_ENABLED @"OFFERS_ENABLED"
55 +#define WL_CONSUMER_DATA_ENABLED @"CONSUMER_DATA_ENABLED"
56 +#define WL_USER_SESSION_ENABLED @"USER_SESSION_ENABLED"
57 +#define WL_CUSTOM_ANALYTICS_ENABLED @"CUSTOM_ANALYTICS_ENABLED"
58 +#define WL_USER_TAGGING_ENABLED @"USER_TAGGING_ENABLED"
59 +#define WL_APPLICATION_DATA_ENABLED @"APPLICATION_DATA_ENABLED"
60 +#define WL_WARPLY_ENABLED @"WARPLY_ENABLED"
61 +#define WL_FEATURES_CHECK_INTERVAL @"FEATURES_CHECK_INTERVAL"
62 +#define WL_LIFECYCLE_ANALYTICS_ENABLED @"LIFECYCLE_ANALYTICS_ENABLED"
63 +#define WL_IOS_LOCATION_FOREGROUND_DESIRED_ACCURACY @"IOS_LOCATION_FOREGROUND_DESIRED_ACCURACY"
64 +#define WL_IOS_LOCATION_BACKGROUND_DESIRED_ACCURACY @"IOS_LOCATION_BACKGROUND_DESIRED_ACCURACY"
65 +#define WL_IOS_DEVICE_IS_WARPED @"is_warped"
66 +#define WL_IOS_DEVICE_HAS_DEVICE_INFO @"has_device_info"
67 +#define WL_IOS_DEVICE_HAS_APPLICATION_INFO @"has_application_info"
68 +#define WL_FEATURE_IS_DISABLED_WITH_KEY(KEY) \
69 + ([[NSUserDefaults standardUserDefaults] boolForKey:KEY] == NO \
70 + && [[NSUserDefaults standardUserDefaults] objectForKey:KEY] != nil) \
71 +
72 +#define WL_WARP_NOTIFICATIONS_ENABLED @"warp_enabled"
73 +#define WL_APPLICATION_DATA @"application_data"
74 +#define WL_DEVICE_STATUS @"device_status"
75 +#define WL_BEACON_ENABLED @"BEACON_ENABLED"
76 +#define WL_BEACON_TIME_INTERVAL_TO_RESEND @"BEACON_TIME_INTERVAL_TO_RESEND"
77 +
78 +///////////////////////////////////////////////////////////////////////////////
79 +// Logging
80 +#ifdef DEBUG
81 +#define WLLOG(xx, ...) NSLog(@"%s(%d): " xx, __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)
82 +#else
83 +#define WLLOG(xx, ...) ((void)0)
84 +#endif // #ifdef DEBUG
85 +
86 +///////////////////////////////////////////////////////////////////////////////
87 +// Version Interface
88 +#define WL_VERSION_INTERFACE() \
89 ++ (NSString *)get;
90 +
91 +#define WL_VERSION_IMPLEMENTATION(VERSION_STR) \
92 ++ (NSString *)get { \
93 + return VERSION_STR; \
94 +} \
95 +
96 +///////////////////////////////////////////////////////////////////////////////
97 +// System Versioning
98 +#define SYSTEM_VERSION_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
99 +#define SYSTEM_VERSION_GREATER_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
100 +#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
101 +#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
102 +#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)
103 +
104 +///////////////////////////////////////////////////////////////////////////////
105 +// Enum Versioning
106 +#ifdef __IPHONE_6_0 // iOS6 and later
107 +# define WLTextAlignmentCenter NSTextAlignmentCenter
108 +# define WLTextAlignmentLeft NSTextAlignmentLeft
109 +# define WLTextAlignmentRight NSTextAlignmentRight
110 +# define WLTextTruncationTail NSLineBreakByTruncatingTail
111 +# define WLTextTruncationMiddle NSLineBreakByWordWrapping
112 +# define WLLineBreakByWordWrapping NSLineBreakByWordWrapping
113 +#else // older versions
114 +# define WLTextAlignmentCenter UITextAlignmentCenter
115 +# define WLTextAlignmentLeft UITextAlignmentLeft
116 +# define WLTextAlignmentRight UITextAlignmentRight
117 +# define WLTextTruncationTail UILineBreakModeTailTruncation
118 +# define WLTextTruncationMiddle UILineBreakModeMiddleTruncation
119 +# define WLLineBreakByWordWrapping UILineBreakModeWordWrap
120 +#endif
1 +/*
2 + Copyright 2010-2016 Warply Inc. All rights reserved.
3 +
4 + Redistribution and use in source and binary forms, without modification,
5 + are permitted provided that the following conditions are met:
6 +
7 + 1. Redistributions of source code must retain the above copyright notice, this
8 + list of conditions and the following disclaimer.
9 +
10 + 2. Redistributions in binaryform must reproduce the above copyright notice,
11 + this list of conditions and the following disclaimer in the documentation
12 + and/or other materials provided with the distribution.
13 +
14 + THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 + EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 + */
25 +
26 +/*!
27 + @header Warply.h
28 + Provides a functional interface for Warply service.
29 + Use the methods declared here to launch or abolish Warply service, access and
30 + manage available functionality managers, add events and send them, get campaigns
31 + inbox and POST/GET context from/to Warply service.
32 + @copyright Warply Inc.
33 + */
34 +#import <Foundation/Foundation.h>
35 +#import "WLGlobals.h"
36 +#import "WLEvent.h"
37 +#import "WLLocationManager.h"
38 +#import "WLAnalyticsManager.h"
39 +#import "FMDatabase.h"
40 +#import "FMDatabaseAdditions.h"
41 +#import "WLPushManager.h"
42 +
43 +@class WLUserManager;
44 +@protocol WLActionHandler;
45 +
46 +/*!
47 + @defined WL_FMDBLogError
48 + @abstract Defines an error logger for the local DB.
49 + */
50 +#define WL_FMDBLogError if ([_db hadError]) { WLLOG(@"Err %d: %@", [_db lastErrorCode], [_db lastErrorMessage]); }
51 +
52 +/*!
53 + @typedef _WLResultCodes
54 + @abstract Warply related custom result codes.
55 + @field WLResultCodesSuccess The call was sucessful.
56 + @field WLResultCodesError The structure or the parameters of the call are wrong.
57 + @field WLResultCodesReadOnly You can read only and not write the selected attribute.
58 + @field WLResultCodesInvalidCampaignID Either the campaing is expired or revoked.
59 + @field WLResultCodesInvalidAppID You need to set the correct app id as shown in Warply.
60 + @field WLResultCodesDeviceRegistrationFailed Check that device token is in correct format.
61 + @field WLResultCodesInvalidJsonPath Check the path you trying to access.
62 + @field WLResultCodesNotImplemented The call doesn't exists yet.
63 + @field WLResultCodesInvalidWebID Need to register device again.
64 + @field WLResultCodesAuthorizationFailed Invalid hash was sent.
65 + @field WLResultCodesNotRegistered Need to register device prior to make the call.
66 + @discussion These result codes are custom and related to Warply service. They
67 + indicate whether a call is sucessfull and if not why it failed.
68 + */
69 +typedef enum {
70 + WLResultCodesSuccess = 1,
71 + WLResultCodesError,
72 + WLResultCodesReadOnly,
73 + WLResultCodesInvalidCampaignID,
74 + WLResultCodesInvalidAppID,
75 + WLResultCodesDeviceRegistrationFailed,
76 + WLResultCodesInvalidJsonPath,
77 + WLResultCodesNotImplemented,
78 + WLResultCodesInvalidWebID,
79 + WLResultCodesAuthorizationFailed,
80 + WLResultCodesNotRegistered
81 +} _WLResultCodes;
82 +
83 +/*!
84 + @typedef WLContextRequestType
85 + @abstract Warply related request types.
86 + @field WLContextRequestTypeGet A GET type request.
87 + @field WLContextRequestTypePost A POST type request.
88 + @discussion These two types of requests indicate whether a request is GET or POST.
89 + */
90 +typedef enum {
91 + WLContextRequestTypeGet,
92 + WLContextRequestTypePost
93 +}WLContextRequestType;
94 +
95 +/*!
96 + @typedef WLServerType
97 + @abstract Warply related servers types.
98 + @field WLServerTypeDevelopment The developement Warply server. Mainly, used for
99 + development and testing.
100 + @field WLServerTypeProduction The production Warply server. Used by all live apps.
101 + */
102 +typedef enum {
103 + WLServerTypeDevelopment = 0,
104 + WLServerTypeProduction
105 +}WLServerType;
106 +
107 +/*!
108 + @defined WLResultCodesDescriptions
109 + @abstract Defines an array of Warply releated results status.
110 + */
111 +#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]
112 +
113 +/*!
114 + @class WLAppService
115 + @discussion The WLAppService provides a functional interface for Warply service.
116 + */
117 +@interface Warply : NSObject
118 +{
119 +@private
120 + //DB
121 + FMDatabase *_db;
122 +
123 + //Services
124 + WLPushManager *_pushManager;
125 + WLLocationManager *_locationManager;
126 +}
127 +
128 +/*!
129 + @methodgroup Getting Shared Instance
130 + */
131 +/*!
132 + @abstract Returns a shared instance of WLAppService.
133 + */
134 ++ (Warply *)sharedService;
135 +/*!
136 + @methodgroup Launching and Abolishing Warp service.
137 + */
138 +/*!
139 + @abstract Launching the Warply service.
140 + @discussion This class method initialises the shared instance of WLAppService,
141 + passes the launch options (if any) to managers in order to handle them and
142 + launches the communication with Warply service using the provided unique app identification.
143 + @param appUUID A string with the unique app identification.
144 + @param launchOptions A dictionary with the application launch options. May be
145 + empty if application launched by user.
146 + */
147 ++ (void)launchWithAppUUID:(NSString *)appUUID launchOptions:(NSDictionary *)launchOptions;
148 +
149 +/*!
150 + @abstract Launching the Warply service.
151 + @discussion This class method initialises the shared instance of WLAppService,
152 + passes the launch options (if any) to managers in order to handle them and
153 + launches the communication with Warply service using the provided unique app identification.
154 + @param launchOptions A dictionary with the application launch options. May be
155 + empty if application launched by user.
156 + @param appUUID A string with the unique app identification.
157 + @param customPushDelegate an class conforming to the WLCustomPushDelegate protocol responsible for handling the push notification.
158 + */
159 ++ (void)launchWithAppUUID:(NSString *)appUUID launchOptions:(NSDictionary *)launchOptions customPushHandler:(id <WLCustomPushHandler>)customPushHandler;
160 +
161 +/*!
162 + @abstract Launching the Warply service.
163 + @discussion This class method initialises the shared instance of WLAppService,
164 + passes the launch options (if any) to managers in order to handle them and
165 + launches the communication with Warply service using the provided unique app identification.
166 + @param launchOptions A dictionary with the application launch options. May be
167 + empty if application launched by user.
168 + @param appUUID A string with the unique app identification.
169 + @param customPushDelegate an class conforming to the WLCustomPushDelegate protocol responsible for handling the push notification.
170 + @param baseUrl: A NSString parameter for defining the base url.
171 + */
172 ++ (void)launchWithAppUUID:(NSString *)appUUID launchOptions:(NSDictionary *)launchOptions customPushDelegate:(id <WLCustomPushHandler>)customPushDelegate serverBaseUrl:(NSString *)baseUrl;
173 +
174 +
175 +/*!
176 + @property baseURL
177 + @abstract A string the url of Warply server. Read-only access.
178 + */
179 +@property (nonatomic, readonly, copy) NSString *baseURL;
180 +
181 +/*!
182 + @property webId
183 + @abstract A string with the unique web id of the device.
184 + */
185 +@property (nonatomic, copy, readonly) NSString *webId;
186 +
187 +/*!
188 + @property apiKey
189 + @abstract A string with the unique identifier of the application.
190 + */
191 +@property (nonatomic, copy) NSString *apiKey;
192 +
193 +//Services
194 +/*!
195 + @property pushManager
196 + @abstract A WLPush Manager for handling received Remote Notifications (Push).
197 + */
198 +@property (nonatomic, strong) WLPushManager *pushManager;
199 +
200 +/*!
201 + @property locationManager
202 + @abstract A WLLocation Manager for handling and reporting device location.
203 + */
204 +@property (nonatomic, readonly, strong) WLLocationManager *locationManager;
205 +
206 +/*!
207 + @property consumerDataManager
208 + @abstract A WLConsumer Manager for handling user name,e-mail and MSISDN.
209 + */
210 +@property (nonatomic, readonly, strong) WLUserManager *consumerDataManager;
211 +
212 +/*!
213 + @property allOffers
214 + @abstract All cached campaigns that the Warply Service provides the application according to the appUUID.
215 + */
216 +@property (nonatomic, strong) NSArray *allOffers;
217 +
218 +
219 +@property (nonatomic, strong) NSArray *allProducts;
220 +
221 +/*!
222 + @defined WL_VERSION_INTERFACE
223 + @abstract Defines macros for geeting the SDK version.
224 + @parseOnly
225 + */
226 +WL_VERSION_INTERFACE()
227 +
228 +/*!
229 + @methodgroup App Lifecycle Methods
230 + @discussion Convenience methods for mananging Managers behaviour and sendining
231 + in-app analytics according to app state.
232 + */
233 +/*!
234 + @abstract Notify that app did enter background.
235 + @discussion This method notifies managers and sends in-app analytic that app did
236 + enter background.
237 + */
238 +- (void)applicationDidEnterBackground;
239 +
240 +/*!
241 + @abstract Notify that app will enter foreground.
242 + @discussion This method notifies managers and sends in-app analytic that app will
243 + enter foreground.
244 + */
245 +- (void)applicationWillEnterForeground;
246 +
247 +/*!
248 + @abstract Notify that app did become active.
249 + @discussion This method notifies managers and sends in-app analytic that app did
250 + become active.
251 + */
252 +- (void)applicationDidBecomeActive;
253 +
254 +/*!
255 + @abstract Notify that app will terminate.
256 + @discussion This method notifies managers and sends in-app analytic that app will
257 + terminate.
258 + */
259 +- (void)applicationWillTerminate;
260 +
261 +/*!
262 + @methodgroup Public API
263 + @discussion Convenience methods for doing the most common tasks
264 + */
265 +/*!
266 + @abstract Send an event.
267 + @discussion This method sends an event. This event is stored into a local DB
268 + and is sent over to Warply service when a threshold of stored events is exceeded or immediately if the priority parameter is YES
269 + @param event A WLEvent object.
270 + @param priority A BOOL value indicating if the event should be sent immediately or not.
271 + @see //apple_ref/occ/cl/WLEvent WLEvent
272 + @seealso //apple_ref/occ/instm/WLAppService/addPriorityEvent: addPriorityEvent:
273 + */
274 +- (void)addEvent:(WLEvent *)event priority:(BOOL)priority;
275 +
276 +/*!
277 + @abstract Get inbox from Warply service.
278 + @attributeblock successBlock This block is called when getInbox is sucessful and returns an array with the available WLInboxItem items.
279 + @attributeblock failureBlock This block is called when getInbox fails and returns an error object with failure code and description.
280 + @see //apple_ref/occ/cl/WLInboxItem WLInboxItem
281 + @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.
282 + @discussion This method gets the inbox with campaigns from Warply service. The
283 + 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.
284 + */
285 +- (BOOL)getInboxWithSuccessBlock:(void (^)(NSArray *list))success failureBlock:(void (^)(NSError *error))failure;
286 +
287 +
288 +- (void)getProductsWithSuccessBlock:(NSString*)filter :(void(^)(NSMutableArray *params))success failureBlock:(void(^)(NSError *error))failure;
289 +
290 +- (void)sendContactWithSuccessBlock:(NSString *)name andEmail:(NSString *)email andMsisdn:msisdn andMessage:message :(void(^)(NSMutableArray *params)) success failureBlock:(void(^)(NSError *error))failure;
291 +
292 +- (void)getContentWithCategoryWithSuccessBlock:(NSString *)category andTags:(NSArray *)tags :(void(^)(NSMutableArray *params)) success failureBlock:(void(^)(NSError *error))failure;
293 +
294 +- (void)getMerchantCategoriesWithSuccessBlock :(void(^)(NSMutableArray *params)) success failureBlock:(void(^)(NSError *error))failure;
295 +
296 +- (void)getMerchantsWithSuccessBlock:(void(^)(NSMutableArray *params)) success failureBlock:(void(^)(NSError *error))failure;
297 +
298 +- (void)getTagsCategoriesWithSuccessBlock :(void(^)(NSMutableArray *tagsCategories))success failureBlock:(void(^)(NSError *error))failure;
299 +
300 +- (void)getTagsWithSuccessBlock :(void(^)(NSMutableArray *tagsCategories))success failureBlock:(void(^)(NSError *error))failure;
301 +
302 +- (void)loginWithSuccessBlock:(NSString*)id andPassword:(NSString*)password andLoginType:(NSString*)loginType :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
303 +
304 +- (void)webAuthorizeWithSuccessBlock:(NSDictionary*)contextResponse andId:(NSString*)id andLoginType:(NSString*)loginType :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
305 +
306 +- (void)tokenWithSuccessBlock:(NSDictionary*)contextResponse andClientId:(NSString*)clientId andClientSecret:(NSString*)clientSecret andLoginType:(NSString*) loginType :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
307 +
308 +- (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;
309 +
310 +- (void)refreshToken:(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
311 +
312 +- (void)changePasswordWithSuccessBlock:(NSString*)oldPassword andNewPassword:(NSString*)newPassword :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
313 +
314 +- (void)getProfileWithSuccessBlock :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
315 +
316 +- (void)editProfileWithSuccessBlock:(NSString*)firstName andLastName:(NSString*)lastName andEmail:(NSString*)email andSalutation:(NSString*)salutation andMsisdn:(NSString*)msisdn
317 + andNickname:(NSString*)nickname andGender:(NSString*)gender andBirthday:(NSString*)birthday andNameDay:(NSString*)nameday andTaxID:(NSString*)taxID andProfileMetadata:(NSDictionary*)profileMetadata optin:(NSNumber*) optin newsLetter:(NSNumber*)newsletter
318 + andSMS:(NSNumber*)sms andSegmentation:(NSNumber*)segmentation andSMSSegmentation:(NSNumber*)smsSegmentation :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
319 +
320 +- (void)changeProfileImageWithSuccessBlock:(NSString*)image andUserId:(NSString*)userId :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
321 +
322 +
323 +- (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;
324 +
325 +- (void)getCardsWithSuccessBlock:(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
326 +
327 +- (void)deleteCardWithSuccessBlock:(NSString*)token :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
328 +
329 +- (void)getCouponsWithSuccessBlock:(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
330 +
331 +- (void)getTransactionHistoryWithSuccessBlock:(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
332 +
333 +- (void)getPointsHistoryWithSuccessBlock:(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
334 +
335 +- (void)verifyTicketWithSuccessBlock:(NSString*)guid :(NSString*)ticket :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
336 +
337 +- (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;
338 +
339 +- (void)getAddressWithSuccessBlock:(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
340 +
341 +- (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;
342 +
343 +- (void)deleteAddressWithSuccessBlock:(NSString*)uuid :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
344 +
345 +- (void)redeemCouponWithSuccessBlock:(NSString*)id andUuid:(NSString*)uuid :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
346 +
347 +- (void)forgotPasswordWithIdWithSuccessBlock:(NSString*)id andConfCode:(NSString*)confCode andOtpUuid:(NSString*)otpUuid :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
348 +
349 +- (void)requestOtpWithMsisdnWithSuccessBlock:(NSString*)msisdn andScope:(NSString*)scope :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
350 +
351 +- (void)resetPasswordWithPasswordWithSuccessBlock:(NSString*)password andConfCode:(NSString*)confCode andOtpUuid:(NSString*)otpUuid andConfToken:(NSString*)confToken :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
352 +
353 +- (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;
354 +/*!
355 + @abstract Get the full page add accordint to the display_type of a campaign.
356 + @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.
357 + @attributeblock failureBlock This block is called when getInbox fails and returns an error object with failure code and description.
358 + @see //apple_ref/occ/cl/WLInboxItem WLInboxItem
359 + @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.
360 + @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.
361 + */
362 +- (BOOL)showFullPageAdIfExists:(void (^)(NSArray *list))success failureBlock:(void (^)(NSError *error))failure;
363 +
364 +/*!
365 + @abstract Get inbox from Warply service by filter.
366 + @attributeblock successBlock This block is called when getInbox is sucessful and returns an array with the avaiable filtered WLInboxItem items.
367 + @attributeblock failureBlock This block is called when getInbox fails and returns an error object with failure code and description.
368 + @see //apple_ref/occ/cl/WLInboxItem WLInboxItem
369 + @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.
370 + */
371 +- (BOOL)getInboxByFilter:(NSString*)filter andValue:(NSString*)value withSuccessBlock:(void (^)(NSArray *list))success failureBlock:(void (^)(NSError *error))failure;
372 +
373 +/*!
374 + @abstract Gets the inbox items that are linked to locations near the given location.
375 + @attributeblock successBlock This block is called when getInbox is sucessful and returns an array with the avaiable WLInboxItem items.
376 + @attributeblock failureBlock This block is called when getInbox fails and returns an error object with failure code and description.
377 + @see //apple_ref/occ/cl/WLInboxItem WLInboxItem
378 + @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.
379 + @discussion This method gets the inbox with campaigns from Warply service. The
380 + 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.
381 + */
382 +- (BOOL)getInboxItemsNearLocation:(CLLocationCoordinate2D)coordinates withSuccessBlock:(void (^)(NSArray *list))success failureBlock:(void (^)(NSError *error))failure;
383 +
384 +/*!
385 + @abstract Gets the inbox items that are linked to locations near user.
386 + @attributeblock successBlock This block is called when getInbox is sucessful and returns an array with the avaiable WLInboxItem items.
387 + @attributeblock failureBlock This block is called when getInbox fails and returns an error object with failure code and description.
388 + @see //apple_ref/occ/cl/WLInboxItem WLInboxItem
389 + @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.
390 + @discussion This method gets the inbox with campaigns from Warply service. The
391 + 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.
392 + */
393 +- (BOOL)getInboxItemsNearMeWithSuccessBlock:(void (^)(NSArray *list))success failureBlock:(void (^)(NSError *error))failure;
394 +
395 +/*
396 + @abstract Get the statistics for the inbox.
397 + @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;
398 + @param failure: A block with an NSError parameter that gets called when the call fails.
399 +*/
400 +- (void)getInboxStatusWithSuccessBlock:(void (^)(int count, int newItems, int unread))success failureBlock:(void (^)(NSError *error))failure;
401 +
402 +
403 +/*!
404 + @methodgroup Low Level API
405 + @discussion Convenience methods for either GET/POST context or send all events
406 + stored in local DB.
407 + */
408 +/*!
409 + @abstract Get context for the specified path.
410 + @param path A string with the path to access and get the value.
411 + @attributeblock successBlock This block is called when getContex is sucessful and returns an id.
412 + @attributeblock failureBlock This block is called when getInbox fails and returns an error object with failure code and description.
413 + @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.
414 + @discussion This method gets the context for the specified path. The success block has a parameter of type
415 + id as the type of the data returned value may differ in each case depending on the specified
416 + 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.
417 + */
418 +- (BOOL)getContextWithPath:(NSString *)path
419 + successBlock:(void (^)(id contextResponse))successBlock
420 + failureBlock:(void (^)(NSError *error))failureBlock;
421 +
422 +/*!
423 + @abstract Post context to a specified path.
424 + @param context The data you want to send to the server under the "context" key.
425 + @attributeblock successBlock This block is called when sendContext is sucessful and returns an id.
426 + @attributeblock failureBlock This block is called when the call fails and returns an error object with failure code and description.
427 + @see //apple_ref/c/tdef/_WLResultCodes WLResultCodes
428 +@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.
429 + @discussion This method post the context for the specified path. Make sure that
430 + the path, you are trying to access, has write and not only read permissions. If
431 + it has only read permsissions the post will fail with WLResultCodesReadOnly error
432 + 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.
433 + */
434 +- (BOOL)sendContext:(NSData*)context
435 + successBlock:(void (^)(NSDictionary *contextResponse))successBlock
436 + failureBlock:(void (^)(NSError *error))failureBlock;
437 +
438 +/*!
439 + @abstract Send all localy stored events to Warply service.
440 + @discussion This method flags and sends all the locally stored events to Warply
441 + service. This happend independent if number of locally stored event threshold
442 + has be reached or not. The events are deleted from local DB only when the call is
443 + sucesful. Otherwise, the events remain stored until either the threshold of stored
444 + events is excited and they automatically send to Warply service or this method is
445 + called again.
446 + @attributeblock completionBlock This block is called when sendAllEvents is sucessful.
447 + @attributeblock failureBlock This block is called when sendAllEvents fails and returns an error object with failure code and description.
448 + */
449 +- (void)sendAllEventsWithCompletionBlock:(void (^)(void))successBlock failureBlock:(void (^)(void))failureBlock;
450 +
451 +//TODO: needs revision
452 +/*!
453 + @abstract Gets the context and updates properties relevant with feature (microapp) and application variables availability .
454 + @attributeblock completionBlock This block is called when the call to the server is completed successfully.
455 + @attributeblock failureBlock This block is called when the call to the server fails.
456 + */
457 +- (void)getAppSettingsWithSuccessBlock:(void (^)(void))success failureBlock:(void(^)(NSError *error))failure;
458 +
459 +// TODO: add documentation
460 +- (void)registerActionHandler:(id <WLActionHandler>)handler;
461 +- (BOOL)handleActionUrl:(NSURL *)url;
462 +
463 +-(BOOL)checkIfUserLoactionIsInPois:(CLLocation *) location;
464 +
465 +@end
466 +
467 +// TODO: add documentation
468 +@protocol WLActionHandler <NSObject>
469 +
470 +- (BOOL)canHandleActionUrl:(NSURL *)url;
471 +- (void)handleActionUrl:(NSURL *)url;
472 +
473 +@end
This diff could not be displayed because it is too large.
1 +/*
2 + Copyright 2010-2016 Warply Inc. All rights reserved.
3 +
4 + Redistribution and use in source and binary forms, without modification,
5 + are permitted provided that the following conditions are met:
6 +
7 + 1. Redistributions of source code must retain the above copyright notice, this
8 + list of conditions and the following disclaimer.
9 +
10 + 2. Redistributions in binaryform must reproduce the above copyright notice,
11 + this list of conditions and the following disclaimer in the documentation
12 + and/or other materials provided with the distribution.
13 +
14 + THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 + EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 + */
25 +
26 +#import <Foundation/Foundation.h>
27 +#import <StoreKit/StoreKit.h>
28 +#import "Warply.h"
29 +
30 +@interface WLAPPActionHandler : NSObject <WLActionHandler,SKStoreProductViewControllerDelegate>
31 +
32 +@end
1 +/*
2 + Copyright 2010-2016 Warply Inc. All rights reserved.
3 +
4 + Redistribution and use in source and binary forms, without modification,
5 + are permitted provided that the following conditions are met:
6 +
7 + 1. Redistributions of source code must retain the above copyright notice, this
8 + list of conditions and the following disclaimer.
9 +
10 + 2. Redistributions in binaryform must reproduce the above copyright notice,
11 + this list of conditions and the following disclaimer in the documentation
12 + and/or other materials provided with the distribution.
13 +
14 + THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 + EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 + */
25 +
26 +#import "WLAPPActionHandler.h"
27 +#import "WLAnalyticsManager.h"
28 +#import "WLInboxItemViewController.h"
29 +#import "NSString+SSToolkitAdditions.h"
30 +#import "UIViewController+WLAdditions.h"
31 +
32 +@interface WLAPPActionHandler ()
33 +
34 +@property (nonatomic, assign) WLInboxItemViewController *inboxVC;
35 +@property (nonatomic) BOOL *loadingProduct;
36 +@end
37 +
38 +
39 +@implementation WLAPPActionHandler
40 +
41 +#pragma mark - Static Methods
42 +////////////////////////////////////////////////////////////////////////////////
43 +- (BOOL)canHandleActionUrl:(NSURL *)url
44 +{
45 + return [url.scheme isEqualToString: @"itms-apps"];
46 +}
47 +
48 +#pragma mark - Override Methods
49 +////////////////////////////////////////////////////////////////////////////////
50 +- (void)handleActionUrl:(NSURL *)url
51 +{
52 + UINavigationController *inboxNavCon = (UINavigationController *)[([UIApplication sharedApplication].delegate).window.rootViewController topModalViewController];
53 + self.inboxVC = [inboxNavCon.viewControllers objectAtIndex:0];
54 +
55 + NSString *appID = nil;
56 +
57 + if ([SKStoreProductViewController class]) {
58 + __block SKStoreProductViewController *storeViewController = [[SKStoreProductViewController alloc] init];
59 + storeViewController.delegate = self;
60 + NSString *escapedResourceSpecifier = [url.resourceSpecifier stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
61 + NSRange appIDRange = [escapedResourceSpecifier rangeOfString:@"id"];
62 + NSRange appQuestionMarkRange = [escapedResourceSpecifier rangeOfString:@"?"];
63 +
64 + if (appIDRange.location != NSNotFound && appQuestionMarkRange.location != NSNotFound) {
65 + appID = [escapedResourceSpecifier substringWithRange:NSMakeRange(appIDRange.location + 2, appQuestionMarkRange.location - (appIDRange.location + 2))];
66 + }
67 +
68 + NSDictionary *parameters = @{SKStoreProductParameterITunesItemIdentifier:[NSNumber numberWithInteger:[appID intValue]]};
69 + [storeViewController loadProductWithParameters:parameters
70 + completionBlock:^(BOOL result, NSError *error) {
71 + if (result) {
72 + [self.inboxVC presentViewController:storeViewController animated:YES completion:nil];
73 + }
74 + }];
75 + } else {
76 + [[UIApplication sharedApplication] openURL:url];
77 + }
78 +
79 + [WLAnalyticsManager logUrgentEventWithEventId:@"NB_CUSTOM_ACTION" pageId:@"APP_DOWNLOAD" actionMetadata:@{@"result":@[@"APPSTORE"], @"session_uuid":self.inboxVC.session_uuid, @"url": [url absoluteString]}];
80 +}
81 +
82 +#pragma mark - SKStoreProductViewControllerDelegate
83 +////////////////////////////////////////////////////////////////////////////////
84 +-(void)productViewControllerDidFinish:(SKStoreProductViewController *)viewController
85 +{
86 + [viewController dismissViewControllerAnimated:YES completion:nil];
87 +}
88 +
89 +@end
1 +/*
2 + Copyright 2010-2016 Warply Inc. All rights reserved.
3 +
4 + Redistribution and use in source and binary forms, without modification,
5 + are permitted provided that the following conditions are met:
6 +
7 + 1. Redistributions of source code must retain the above copyright notice, this
8 + list of conditions and the following disclaimer.
9 +
10 + 2. Redistributions in binaryform must reproduce the above copyright notice,
11 + this list of conditions and the following disclaimer in the documentation
12 + and/or other materials provided with the distribution.
13 +
14 + THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 + EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 + */
25 +
26 +#import <MessageUI/MessageUI.h>
27 +#import "Warply.h"
28 +
29 +@interface WLSMSActionHandlerDeprecated : NSObject <MFMessageComposeViewControllerDelegate, WLActionHandler>
30 +
31 +@end
1 +/*
2 + Copyright 2010-2016 Warply Inc. All rights reserved.
3 +
4 + Redistribution and use in source and binary forms, without modification,
5 + are permitted provided that the following conditions are met:
6 +
7 + 1. Redistributions of source code must retain the above copyright notice, this
8 + list of conditions and the following disclaimer.
9 +
10 + 2. Redistributions in binaryform must reproduce the above copyright notice,
11 + this list of conditions and the following disclaimer in the documentation
12 + and/or other materials provided with the distribution.
13 +
14 + THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 + EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 + */
25 +
26 +#import "WLSMSActionHandlerDeprecated.h"
27 +#import "WLGlobals.h"
28 +#import "WLInboxItemViewController.h"
29 +#import "UIViewController+WLAdditions.h"
30 +
31 +@interface WLSMSActionHandlerDeprecated ()
32 +@property (nonatomic , weak) WLInboxItemViewController *inboxVC;
33 +@end
34 +
35 +@implementation WLSMSActionHandlerDeprecated
36 +
37 +#pragma mark - Static Methods
38 +///////////////////////////////////////////////////////////////////////////////////////////////////
39 +- (BOOL)canHandleActionUrl:(NSURL *)url
40 +{
41 + return [[url scheme] isEqualToString: @"rsms"];
42 +}
43 +
44 +#pragma mark - Override Methods
45 +///////////////////////////////////////////////////////////////////////////////////////////////////
46 +- (void)handleActionUrl:(NSURL *)url
47 +{
48 + self.inboxVC = (WLInboxItemViewController *)[([UIApplication sharedApplication].delegate).window.rootViewController topModalViewController];
49 +
50 +
51 + NSArray *args = [url.resourceSpecifier componentsSeparatedByString:@"/"];
52 + if (args == nil)
53 + return;
54 +
55 + if ([args count] < 4)
56 + return;
57 +
58 + MFMessageComposeViewController *smsController = [[MFMessageComposeViewController alloc] init];
59 + @try {
60 + [smsController setRecipients:[NSArray arrayWithObject:[args objectAtIndex:4]]];
61 + //[smsController setBody:[NSString stringWithFormat:@"Hello from %@", BRAND_NAME]];
62 +
63 + if ([args count] > 4) {
64 + NSString *body = [[args objectAtIndex:5] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
65 + [smsController setBody:body];
66 + }
67 +
68 + [smsController setMessageComposeDelegate:self];
69 + [_inboxVC presentViewController:smsController animated:YES completion:nil];
70 + }
71 + @finally {
72 +
73 + }
74 +}
75 +
76 +#pragma mark - MFMessageComposeViewControllerDelegate
77 +///////////////////////////////////////////////////////////////////////////////////////////////////
78 +- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
79 +{
80 + WLInboxItemViewController *inboxItemViewController = (WLInboxItemViewController *)[([UIApplication sharedApplication].delegate).window.rootViewController topModalViewController];
81 + NSString *resultString;
82 + switch (result) {
83 + case MessageComposeResultCancelled:
84 + resultString = @"sms_cancelled";
85 + break;
86 + case MessageComposeResultFailed:
87 + resultString = @"sms_failed";
88 + break;
89 + case MessageComposeResultSent:
90 + resultString = @"sms_sent";
91 + }
92 + [WLAnalyticsManager logEventWithEventId:@"NB_ACTION" pageId:inboxItemViewController.session_uuid actionMetadata:[NSDictionary dictionaryWithObjectsAndKeys:resultString, @"sms_result", self.inboxVC.requestedUrl.absoluteString, @"action_url", nil]];
93 + [controller dismissViewControllerAnimated:YES completion:nil];
94 +}
95 +
96 +@end
1 +/*
2 + Copyright 2010-2016 Warply Inc. All rights reserved.
3 +
4 + Redistribution and use in source and binary forms, without modification,
5 + are permitted provided that the following conditions are met:
6 +
7 + 1. Redistributions of source code must retain the above copyright notice, this
8 + list of conditions and the following disclaimer.
9 +
10 + 2. Redistributions in binaryform must reproduce the above copyright notice,
11 + this list of conditions and the following disclaimer in the documentation
12 + and/or other materials provided with the distribution.
13 +
14 + THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 + EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 + */
25 +
26 +#import <MessageUI/MessageUI.h>
27 +#import "Warply.h"
28 +
29 +@interface WLSMSActionHanlder : NSObject <MFMessageComposeViewControllerDelegate, WLActionHandler>
30 +
31 +@end
...\ No newline at end of file ...\ No newline at end of file
1 +/*
2 + Copyright 2010-2016 Warply Inc. All rights reserved.
3 +
4 + Redistribution and use in source and binary forms, without modification,
5 + are permitted provided that the following conditions are met:
6 +
7 + 1. Redistributions of source code must retain the above copyright notice, this
8 + list of conditions and the following disclaimer.
9 +
10 + 2. Redistributions in binaryform must reproduce the above copyright notice,
11 + this list of conditions and the following disclaimer in the documentation
12 + and/or other materials provided with the distribution.
13 +
14 + THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 + EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 + */
25 +
26 +#import "WLSMSActionHanlder.h"
27 +#import "WLGlobals.h"
28 +#import "WLAnalyticsManager.h"
29 +#import "WLInboxItemViewController.h"
30 +#import "WLBaseItem.h"
31 +#import "UIViewController+WLAdditions.h"
32 +
33 +@interface WLSMSActionHanlder ()
34 +
35 +@property (nonatomic, weak) WLInboxItemViewController *inboxVC;
36 +
37 +@end
38 +
39 +@implementation WLSMSActionHanlder
40 +
41 +#pragma mark - Static Methods
42 +///////////////////////////////////////////////////////////////////////////////////////////////////
43 +- (BOOL)canHandleActionUrl:(NSURL *)url
44 +{
45 + return [url.scheme isEqualToString: @"sms"];
46 +}
47 +
48 +#pragma mark - Override Methods
49 +///////////////////////////////////////////////////////////////////////////////////////////////////
50 +- (void)handleActionUrl:(NSURL *)url
51 +{
52 + UINavigationController *inboxNavCon = (UINavigationController *)[([UIApplication sharedApplication].delegate).window.rootViewController topModalViewController];
53 + self.inboxVC = [inboxNavCon.viewControllers objectAtIndex:0];
54 +
55 + if (![MFMessageComposeViewController canSendText]) {
56 + UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"This device does not support text messages", @"Warply") message:nil delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", @"Warply") otherButtonTitles:nil];
57 + [alert show];
58 +
59 + return;
60 + }
61 +
62 + WLLOG(@"SMS URI: %@", url.absoluteString);
63 + if (url.resourceSpecifier == nil) {
64 + return;
65 + }
66 + NSString *escapedResourceSpecifier = [url.resourceSpecifier stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
67 + NSArray *args = [escapedResourceSpecifier componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"?&"]];
68 + NSString *recipientsString = [args objectAtIndex:0];
69 + NSArray *recipients = [recipientsString componentsSeparatedByString:@","];
70 + NSString *bodyString = nil;
71 +
72 + for (NSString *argument in args) {
73 + if ([argument isEqualToString:recipientsString]) {
74 + continue;
75 + }
76 + NSRange bodyKeyRange = [argument rangeOfString:@"body="];
77 + if (bodyKeyRange.location != NSNotFound) {
78 + bodyString = [argument substringFromIndex:bodyKeyRange.length];
79 + }
80 + }
81 +
82 + MFMessageComposeViewController *smsController = [[MFMessageComposeViewController alloc] init];
83 + [smsController setRecipients:recipients];
84 + [smsController setBody:bodyString];
85 +
86 + [smsController setMessageComposeDelegate:self];
87 + [_inboxVC presentViewController:smsController animated:YES completion:nil];
88 +
89 +}
90 +
91 +#pragma mark - MFMessageComposeViewControllerDelegate
92 +///////////////////////////////////////////////////////////////////////////////////////////////////
93 +- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
94 +{
95 + NSArray *results;
96 + switch (result) {
97 + case MessageComposeResultCancelled:
98 + results = @[@"sms_prompt_clicked", @"sms_cancelled"];
99 + break;
100 + case MessageComposeResultFailed:
101 + results = @[@"sms_prompt_clicked", @"sms_failed"];
102 + break;
103 + case MessageComposeResultSent:
104 + results = @[@"sms_prompt_clicked", @"sms_sent"];
105 + }
106 + [WLAnalyticsManager logUrgentEventWithEventId:@"NB_CUSTOM_ACTION" pageId:@"SMS" actionMetadata:@{@"session_uuid": self.inboxVC.session_uuid, @"result":results}];
107 + [controller dismissViewControllerAnimated:YES completion:nil];
108 +}
109 +
110 +@end
1 +// AFHTTPSessionManager.h
2 +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 +//
4 +// Permission is hereby granted, free of charge, to any person obtaining a copy
5 +// of this software and associated documentation files (the "Software"), to deal
6 +// in the Software without restriction, including without limitation the rights
7 +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 +// copies of the Software, and to permit persons to whom the Software is
9 +// furnished to do so, subject to the following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included in
12 +// all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 +// THE SOFTWARE.
21 +
22 +#import <Foundation/Foundation.h>
23 +#if !TARGET_OS_WATCH
24 +#import <SystemConfiguration/SystemConfiguration.h>
25 +#endif
26 +#import <TargetConditionals.h>
27 +
28 +#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV
29 +#import <MobileCoreServices/MobileCoreServices.h>
30 +#else
31 +#import <CoreServices/CoreServices.h>
32 +#endif
33 +
34 +#import "AFURLSessionManager.h"
35 +
36 +/**
37 + `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.
38 +
39 + ## Subclassing Notes
40 +
41 + 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.
42 +
43 + For developers targeting iOS 6 or Mac OS X 10.8 or earlier, `AFHTTPRequestOperationManager` may be used to similar effect.
44 +
45 + ## Methods to Override
46 +
47 + 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:`.
48 +
49 + ## Serialization
50 +
51 + 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>`.
52 +
53 + Responses received from the server are automatically validated and serialized by the `responseSerializers` property, which is an object conforming to `<AFURLResponseSerialization>`
54 +
55 + ## URL Construction Using Relative Paths
56 +
57 + 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:`.
58 +
59 + Below are a few examples of how `baseURL` and relative paths interact:
60 +
61 + NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"];
62 + [NSURL URLWithString:@"foo" relativeToURL:baseURL]; // http://example.com/v1/foo
63 + [NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL]; // http://example.com/v1/foo?bar=baz
64 + [NSURL URLWithString:@"/foo" relativeToURL:baseURL]; // http://example.com/foo
65 + [NSURL URLWithString:@"foo/" relativeToURL:baseURL]; // http://example.com/v1/foo
66 + [NSURL URLWithString:@"/foo/" relativeToURL:baseURL]; // http://example.com/foo/
67 + [NSURL URLWithString:@"http://example2.com/" relativeToURL:baseURL]; // http://example2.com/
68 +
69 + 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.
70 +
71 + @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.
72 + */
73 +
74 +NS_ASSUME_NONNULL_BEGIN
75 +
76 +@interface AFHTTPSessionManager : AFURLSessionManager <NSSecureCoding, NSCopying>
77 +
78 +/**
79 + The URL used to construct requests from relative paths in methods like `requestWithMethod:URLString:parameters:`, and the `GET` / `POST` / et al. convenience methods.
80 + */
81 +@property (readonly, nonatomic, strong, nullable) NSURL *baseURL;
82 +
83 +/**
84 + 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.
85 +
86 + @warning `requestSerializer` must not be `nil`.
87 + */
88 +@property (nonatomic, strong) AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer;
89 +
90 +/**
91 + 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`.
92 +
93 + @warning `responseSerializer` must not be `nil`.
94 + */
95 +@property (nonatomic, strong) AFHTTPResponseSerializer <AFURLResponseSerialization> * responseSerializer;
96 +
97 +///-------------------------------
98 +/// @name Managing Security Policy
99 +///-------------------------------
100 +
101 +/**
102 + 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.
103 + */
104 +@property (nonatomic, strong) AFSecurityPolicy *securityPolicy;
105 +
106 +///---------------------
107 +/// @name Initialization
108 +///---------------------
109 +
110 +/**
111 + Creates and returns an `AFHTTPSessionManager` object.
112 + */
113 ++ (instancetype)manager;
114 +
115 +/**
116 + Initializes an `AFHTTPSessionManager` object with the specified base URL.
117 +
118 + @param url The base URL for the HTTP client.
119 +
120 + @return The newly-initialized HTTP client
121 + */
122 +- (instancetype)initWithBaseURL:(nullable NSURL *)url;
123 +
124 +/**
125 + Initializes an `AFHTTPSessionManager` object with the specified base URL.
126 +
127 + This is the designated initializer.
128 +
129 + @param url The base URL for the HTTP client.
130 + @param configuration The configuration used to create the managed session.
131 +
132 + @return The newly-initialized HTTP client
133 + */
134 +- (instancetype)initWithBaseURL:(nullable NSURL *)url
135 + sessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER;
136 +
137 +///---------------------------
138 +/// @name Making HTTP Requests
139 +///---------------------------
140 +
141 +/**
142 + Creates and runs an `NSURLSessionDataTask` with a `GET` request.
143 +
144 + @param URLString The URL string used to create the request URL.
145 + @param parameters The parameters to be encoded according to the client request serializer.
146 + @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.
147 + @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.
148 +
149 + @see -dataTaskWithRequest:completionHandler:
150 + */
151 +- (nullable NSURLSessionDataTask *)GET:(NSString *)URLString
152 + parameters:(nullable id)parameters
153 + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
154 + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure DEPRECATED_ATTRIBUTE;
155 +
156 +
157 +/**
158 + Creates and runs an `NSURLSessionDataTask` with a `GET` request.
159 +
160 + @param URLString The URL string used to create the request URL.
161 + @param parameters The parameters to be encoded according to the client request serializer.
162 + @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.
163 + @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.
164 + @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.
165 +
166 + @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:
167 + */
168 +- (nullable NSURLSessionDataTask *)GET:(NSString *)URLString
169 + parameters:(nullable id)parameters
170 + progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgress
171 + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
172 + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
173 +
174 +/**
175 + Creates and runs an `NSURLSessionDataTask` with a `HEAD` request.
176 +
177 + @param URLString The URL string used to create the request URL.
178 + @param parameters The parameters to be encoded according to the client request serializer.
179 + @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.
180 + @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.
181 +
182 + @see -dataTaskWithRequest:completionHandler:
183 + */
184 +- (nullable NSURLSessionDataTask *)HEAD:(NSString *)URLString
185 + parameters:(nullable id)parameters
186 + success:(nullable void (^)(NSURLSessionDataTask *task))success
187 + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
188 +
189 +/**
190 + Creates and runs an `NSURLSessionDataTask` with a `POST` request.
191 +
192 + @param URLString The URL string used to create the request URL.
193 + @param parameters The parameters to be encoded according to the client request serializer.
194 + @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.
195 + @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.
196 +
197 + @see -dataTaskWithRequest:completionHandler:
198 + */
199 +- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString
200 + parameters:(nullable id)parameters
201 + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
202 + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure DEPRECATED_ATTRIBUTE;
203 +
204 +/**
205 + Creates and runs an `NSURLSessionDataTask` with a `POST` request.
206 +
207 + @param URLString The URL string used to create the request URL.
208 + @param parameters The parameters to be encoded according to the client request serializer.
209 + @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.
210 + @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.
211 + @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.
212 +
213 + @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:
214 + */
215 +- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString
216 + parameters:(nullable id)parameters
217 + progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress
218 + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
219 + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
220 +
221 +/**
222 + Creates and runs an `NSURLSessionDataTask` with a multipart `POST` request.
223 +
224 + @param URLString The URL string used to create the request URL.
225 + @param parameters The parameters to be encoded according to the client request serializer.
226 + @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.
227 + @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.
228 + @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.
229 +
230 + @see -dataTaskWithRequest:completionHandler:
231 + */
232 +- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString
233 + parameters:(nullable id)parameters
234 + constructingBodyWithBlock:(nullable void (^)(id <AFMultipartFormData> formData))block
235 + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
236 + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure DEPRECATED_ATTRIBUTE;
237 +
238 +/**
239 + Creates and runs an `NSURLSessionDataTask` with a multipart `POST` request.
240 +
241 + @param URLString The URL string used to create the request URL.
242 + @param parameters The parameters to be encoded according to the client request serializer.
243 + @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.
244 + @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.
245 + @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.
246 + @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.
247 +
248 + @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:
249 + */
250 +- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString
251 + parameters:(nullable id)parameters
252 + constructingBodyWithBlock:(nullable void (^)(id <AFMultipartFormData> formData))block
253 + progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress
254 + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
255 + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
256 +
257 +/**
258 + Creates and runs an `NSURLSessionDataTask` with a `PUT` request.
259 +
260 + @param URLString The URL string used to create the request URL.
261 + @param parameters The parameters to be encoded according to the client request serializer.
262 + @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.
263 + @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.
264 +
265 + @see -dataTaskWithRequest:completionHandler:
266 + */
267 +- (nullable NSURLSessionDataTask *)PUT:(NSString *)URLString
268 + parameters:(nullable id)parameters
269 + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
270 + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
271 +
272 +/**
273 + Creates and runs an `NSURLSessionDataTask` with a `PATCH` request.
274 +
275 + @param URLString The URL string used to create the request URL.
276 + @param parameters The parameters to be encoded according to the client request serializer.
277 + @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.
278 + @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.
279 +
280 + @see -dataTaskWithRequest:completionHandler:
281 + */
282 +- (nullable NSURLSessionDataTask *)PATCH:(NSString *)URLString
283 + parameters:(nullable id)parameters
284 + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
285 + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
286 +
287 +/**
288 + Creates and runs an `NSURLSessionDataTask` with a `DELETE` request.
289 +
290 + @param URLString The URL string used to create the request URL.
291 + @param parameters The parameters to be encoded according to the client request serializer.
292 + @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.
293 + @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.
294 +
295 + @see -dataTaskWithRequest:completionHandler:
296 + */
297 +- (nullable NSURLSessionDataTask *)DELETE:(NSString *)URLString
298 + parameters:(nullable id)parameters
299 + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
300 + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
301 +
302 +@end
303 +
304 +NS_ASSUME_NONNULL_END
1 +// AFHTTPSessionManager.m
2 +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 +//
4 +// Permission is hereby granted, free of charge, to any person obtaining a copy
5 +// of this software and associated documentation files (the "Software"), to deal
6 +// in the Software without restriction, including without limitation the rights
7 +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 +// copies of the Software, and to permit persons to whom the Software is
9 +// furnished to do so, subject to the following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included in
12 +// all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 +// THE SOFTWARE.
21 +
22 +#import "AFHTTPSessionManager.h"
23 +
24 +#import "AFURLRequestSerialization.h"
25 +#import "AFURLResponseSerialization.h"
26 +
27 +#import <Availability.h>
28 +#import <TargetConditionals.h>
29 +#import <Security/Security.h>
30 +
31 +#import <netinet/in.h>
32 +#import <netinet6/in6.h>
33 +#import <arpa/inet.h>
34 +#import <ifaddrs.h>
35 +#import <netdb.h>
36 +
37 +#if TARGET_OS_IOS || TARGET_OS_TV
38 +#import <UIKit/UIKit.h>
39 +#elif TARGET_OS_WATCH
40 +#import <WatchKit/WatchKit.h>
41 +#endif
42 +
43 +@interface AFHTTPSessionManager ()
44 +@property (readwrite, nonatomic, strong) NSURL *baseURL;
45 +@end
46 +
47 +@implementation AFHTTPSessionManager
48 +@dynamic responseSerializer;
49 +
50 ++ (instancetype)manager {
51 + return [[[self class] alloc] initWithBaseURL:nil];
52 +}
53 +
54 +- (instancetype)init {
55 + return [self initWithBaseURL:nil];
56 +}
57 +
58 +- (instancetype)initWithBaseURL:(NSURL *)url {
59 + return [self initWithBaseURL:url sessionConfiguration:nil];
60 +}
61 +
62 +- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration {
63 + return [self initWithBaseURL:nil sessionConfiguration:configuration];
64 +}
65 +
66 +- (instancetype)initWithBaseURL:(NSURL *)url
67 + sessionConfiguration:(NSURLSessionConfiguration *)configuration
68 +{
69 + self = [super initWithSessionConfiguration:configuration];
70 + if (!self) {
71 + return nil;
72 + }
73 +
74 + // Ensure terminal slash for baseURL path, so that NSURL +URLWithString:relativeToURL: works as expected
75 + if ([[url path] length] > 0 && ![[url absoluteString] hasSuffix:@"/"]) {
76 + url = [url URLByAppendingPathComponent:@""];
77 + }
78 +
79 + self.baseURL = url;
80 +
81 + self.requestSerializer = [AFHTTPRequestSerializer serializer];
82 + self.responseSerializer = [AFJSONResponseSerializer serializer];
83 +
84 + return self;
85 +}
86 +
87 +#pragma mark -
88 +
89 +- (void)setRequestSerializer:(AFHTTPRequestSerializer <AFURLRequestSerialization> *)requestSerializer {
90 + NSParameterAssert(requestSerializer);
91 +
92 + _requestSerializer = requestSerializer;
93 +}
94 +
95 +- (void)setResponseSerializer:(AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer {
96 + NSParameterAssert(responseSerializer);
97 +
98 + [super setResponseSerializer:responseSerializer];
99 +}
100 +
101 +@dynamic securityPolicy;
102 +
103 +- (void)setSecurityPolicy:(AFSecurityPolicy *)securityPolicy {
104 + if (securityPolicy.SSLPinningMode != AFSSLPinningModeNone && ![self.baseURL.scheme isEqualToString:@"https"]) {
105 + NSString *pinningMode = @"Unknown Pinning Mode";
106 + switch (securityPolicy.SSLPinningMode) {
107 + case AFSSLPinningModeNone: pinningMode = @"AFSSLPinningModeNone"; break;
108 + case AFSSLPinningModeCertificate: pinningMode = @"AFSSLPinningModeCertificate"; break;
109 + case AFSSLPinningModePublicKey: pinningMode = @"AFSSLPinningModePublicKey"; break;
110 + }
111 + 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];
112 + @throw [NSException exceptionWithName:@"Invalid Security Policy" reason:reason userInfo:nil];
113 + }
114 +
115 + [super setSecurityPolicy:securityPolicy];
116 +}
117 +
118 +#pragma mark -
119 +
120 +- (NSURLSessionDataTask *)GET:(NSString *)URLString
121 + parameters:(id)parameters
122 + success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
123 + failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
124 +{
125 +
126 + return [self GET:URLString parameters:parameters progress:nil success:success failure:failure];
127 +}
128 +
129 +- (NSURLSessionDataTask *)GET:(NSString *)URLString
130 + parameters:(id)parameters
131 + progress:(void (^)(NSProgress * _Nonnull))downloadProgress
132 + success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
133 + failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
134 +{
135 +
136 + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"GET"
137 + URLString:URLString
138 + parameters:parameters
139 + uploadProgress:nil
140 + downloadProgress:downloadProgress
141 + success:success
142 + failure:failure];
143 +
144 + [dataTask resume];
145 +
146 + return dataTask;
147 +}
148 +
149 +- (NSURLSessionDataTask *)HEAD:(NSString *)URLString
150 + parameters:(id)parameters
151 + success:(void (^)(NSURLSessionDataTask *task))success
152 + failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
153 +{
154 + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"HEAD" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:^(NSURLSessionDataTask *task, __unused id responseObject) {
155 + if (success) {
156 + success(task);
157 + }
158 + } failure:failure];
159 +
160 + [dataTask resume];
161 +
162 + return dataTask;
163 +}
164 +
165 +- (NSURLSessionDataTask *)POST:(NSString *)URLString
166 + parameters:(id)parameters
167 + success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
168 + failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
169 +{
170 + return [self POST:URLString parameters:parameters progress:nil success:success failure:failure];
171 +}
172 +
173 +- (NSURLSessionDataTask *)POST:(NSString *)URLString
174 + parameters:(id)parameters
175 + progress:(void (^)(NSProgress * _Nonnull))uploadProgress
176 + success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
177 + failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
178 +{
179 + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"POST" URLString:URLString parameters:parameters uploadProgress:uploadProgress downloadProgress:nil success:success failure:failure];
180 +
181 + [dataTask resume];
182 +
183 + return dataTask;
184 +}
185 +
186 +- (NSURLSessionDataTask *)POST:(NSString *)URLString
187 + parameters:(nullable id)parameters
188 + constructingBodyWithBlock:(nullable void (^)(id<AFMultipartFormData> _Nonnull))block
189 + success:(nullable void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
190 + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
191 +{
192 + return [self POST:URLString parameters:parameters constructingBodyWithBlock:block progress:nil success:success failure:failure];
193 +}
194 +
195 +- (NSURLSessionDataTask *)POST:(NSString *)URLString
196 + parameters:(id)parameters
197 + constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
198 + progress:(nullable void (^)(NSProgress * _Nonnull))uploadProgress
199 + success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
200 + failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
201 +{
202 + NSError *serializationError = nil;
203 + NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError];
204 + if (serializationError) {
205 + if (failure) {
206 + dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
207 + failure(nil, serializationError);
208 + });
209 + }
210 +
211 + return nil;
212 + }
213 +
214 + __block NSURLSessionDataTask *task = [self uploadTaskWithStreamedRequest:request progress:uploadProgress completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
215 + if (error) {
216 + if (failure) {
217 + failure(task, error);
218 + }
219 + } else {
220 + if (success) {
221 + success(task, responseObject);
222 + }
223 + }
224 + }];
225 +
226 + [task resume];
227 +
228 + return task;
229 +}
230 +
231 +- (NSURLSessionDataTask *)PUT:(NSString *)URLString
232 + parameters:(id)parameters
233 + success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
234 + failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
235 +{
236 + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PUT" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure];
237 +
238 + [dataTask resume];
239 +
240 + return dataTask;
241 +}
242 +
243 +- (NSURLSessionDataTask *)PATCH:(NSString *)URLString
244 + parameters:(id)parameters
245 + success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
246 + failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
247 +{
248 + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PATCH" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure];
249 +
250 + [dataTask resume];
251 +
252 + return dataTask;
253 +}
254 +
255 +- (NSURLSessionDataTask *)DELETE:(NSString *)URLString
256 + parameters:(id)parameters
257 + success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
258 + failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
259 +{
260 + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"DELETE" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure];
261 +
262 + [dataTask resume];
263 +
264 + return dataTask;
265 +}
266 +
267 +- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
268 + URLString:(NSString *)URLString
269 + parameters:(id)parameters
270 + uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress
271 + downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress
272 + success:(void (^)(NSURLSessionDataTask *, id))success
273 + failure:(void (^)(NSURLSessionDataTask *, NSError *))failure
274 +{
275 + NSError *serializationError = nil;
276 + NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError];
277 + if (serializationError) {
278 + if (failure) {
279 + dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
280 + failure(nil, serializationError);
281 + });
282 + }
283 +
284 + return nil;
285 + }
286 +
287 + __block NSURLSessionDataTask *dataTask = nil;
288 + dataTask = [self dataTaskWithRequest:request
289 + uploadProgress:uploadProgress
290 + downloadProgress:downloadProgress
291 + completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
292 + if (error) {
293 + if (failure) {
294 + failure(dataTask, error);
295 + }
296 + } else {
297 + if (success) {
298 + success(dataTask, responseObject);
299 + }
300 + }
301 + }];
302 +
303 + return dataTask;
304 +}
305 +
306 +#pragma mark - NSObject
307 +
308 +- (NSString *)description {
309 + return [NSString stringWithFormat:@"<%@: %p, baseURL: %@, session: %@, operationQueue: %@>", NSStringFromClass([self class]), self, [self.baseURL absoluteString], self.session, self.operationQueue];
310 +}
311 +
312 +#pragma mark - NSSecureCoding
313 +
314 ++ (BOOL)supportsSecureCoding {
315 + return YES;
316 +}
317 +
318 +- (instancetype)initWithCoder:(NSCoder *)decoder {
319 + NSURL *baseURL = [decoder decodeObjectOfClass:[NSURL class] forKey:NSStringFromSelector(@selector(baseURL))];
320 + NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"];
321 + if (!configuration) {
322 + NSString *configurationIdentifier = [decoder decodeObjectOfClass:[NSString class] forKey:@"identifier"];
323 + if (configurationIdentifier) {
324 +#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)
325 + configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:configurationIdentifier];
326 +#else
327 + configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:configurationIdentifier];
328 +#endif
329 + }
330 + }
331 +
332 + self = [self initWithBaseURL:baseURL sessionConfiguration:configuration];
333 + if (!self) {
334 + return nil;
335 + }
336 +
337 + self.requestSerializer = [decoder decodeObjectOfClass:[AFHTTPRequestSerializer class] forKey:NSStringFromSelector(@selector(requestSerializer))];
338 + self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))];
339 + AFSecurityPolicy *decodedPolicy = [decoder decodeObjectOfClass:[AFSecurityPolicy class] forKey:NSStringFromSelector(@selector(securityPolicy))];
340 + if (decodedPolicy) {
341 + self.securityPolicy = decodedPolicy;
342 + }
343 +
344 + return self;
345 +}
346 +
347 +- (void)encodeWithCoder:(NSCoder *)coder {
348 + [super encodeWithCoder:coder];
349 +
350 + [coder encodeObject:self.baseURL forKey:NSStringFromSelector(@selector(baseURL))];
351 + if ([self.session.configuration conformsToProtocol:@protocol(NSCoding)]) {
352 + [coder encodeObject:self.session.configuration forKey:@"sessionConfiguration"];
353 + } else {
354 + [coder encodeObject:self.session.configuration.identifier forKey:@"identifier"];
355 + }
356 + [coder encodeObject:self.requestSerializer forKey:NSStringFromSelector(@selector(requestSerializer))];
357 + [coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))];
358 + [coder encodeObject:self.securityPolicy forKey:NSStringFromSelector(@selector(securityPolicy))];
359 +}
360 +
361 +#pragma mark - NSCopying
362 +
363 +- (instancetype)copyWithZone:(NSZone *)zone {
364 + AFHTTPSessionManager *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL sessionConfiguration:self.session.configuration];
365 +
366 + HTTPClient.requestSerializer = [self.requestSerializer copyWithZone:zone];
367 + HTTPClient.responseSerializer = [self.responseSerializer copyWithZone:zone];
368 + HTTPClient.securityPolicy = [self.securityPolicy copyWithZone:zone];
369 + return HTTPClient;
370 +}
371 +
372 +@end
1 +// AFNetworkReachabilityManager.h
2 +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 +//
4 +// Permission is hereby granted, free of charge, to any person obtaining a copy
5 +// of this software and associated documentation files (the "Software"), to deal
6 +// in the Software without restriction, including without limitation the rights
7 +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 +// copies of the Software, and to permit persons to whom the Software is
9 +// furnished to do so, subject to the following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included in
12 +// all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 +// THE SOFTWARE.
21 +
22 +#import <Foundation/Foundation.h>
23 +
24 +#if !TARGET_OS_WATCH
25 +#import <SystemConfiguration/SystemConfiguration.h>
26 +
27 +typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
28 + AFNetworkReachabilityStatusUnknown = -1,
29 + AFNetworkReachabilityStatusNotReachable = 0,
30 + AFNetworkReachabilityStatusReachableViaWWAN = 1,
31 + AFNetworkReachabilityStatusReachableViaWiFi = 2,
32 +};
33 +
34 +NS_ASSUME_NONNULL_BEGIN
35 +
36 +/**
37 + `AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces.
38 +
39 + 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.
40 +
41 + See Apple's Reachability Sample Code ( https://developer.apple.com/library/ios/samplecode/reachability/ )
42 +
43 + @warning Instances of `AFNetworkReachabilityManager` must be started with `-startMonitoring` before reachability status can be determined.
44 + */
45 +@interface AFNetworkReachabilityManager : NSObject
46 +
47 +/**
48 + The current network reachability status.
49 + */
50 +@property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;
51 +
52 +/**
53 + Whether or not the network is currently reachable.
54 + */
55 +@property (readonly, nonatomic, assign, getter = isReachable) BOOL reachable;
56 +
57 +/**
58 + Whether or not the network is currently reachable via WWAN.
59 + */
60 +@property (readonly, nonatomic, assign, getter = isReachableViaWWAN) BOOL reachableViaWWAN;
61 +
62 +/**
63 + Whether or not the network is currently reachable via WiFi.
64 + */
65 +@property (readonly, nonatomic, assign, getter = isReachableViaWiFi) BOOL reachableViaWiFi;
66 +
67 +///---------------------
68 +/// @name Initialization
69 +///---------------------
70 +
71 +/**
72 + Returns the shared network reachability manager.
73 + */
74 ++ (instancetype)sharedManager;
75 +
76 +/**
77 + Creates and returns a network reachability manager with the default socket address.
78 +
79 + @return An initialized network reachability manager, actively monitoring the default socket address.
80 + */
81 ++ (instancetype)manager;
82 +
83 +/**
84 + Creates and returns a network reachability manager for the specified domain.
85 +
86 + @param domain The domain used to evaluate network reachability.
87 +
88 + @return An initialized network reachability manager, actively monitoring the specified domain.
89 + */
90 ++ (instancetype)managerForDomain:(NSString *)domain;
91 +
92 +/**
93 + Creates and returns a network reachability manager for the socket address.
94 +
95 + @param address The socket address (`sockaddr_in6`) used to evaluate network reachability.
96 +
97 + @return An initialized network reachability manager, actively monitoring the specified socket address.
98 + */
99 ++ (instancetype)managerForAddress:(const void *)address;
100 +
101 +/**
102 + Initializes an instance of a network reachability manager from the specified reachability object.
103 +
104 + @param reachability The reachability object to monitor.
105 +
106 + @return An initialized network reachability manager, actively monitoring the specified reachability.
107 + */
108 +- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability NS_DESIGNATED_INITIALIZER;
109 +
110 +/**
111 + * Initializes an instance of a network reachability manager
112 + *
113 + * @return nil as this method is unavailable
114 + */
115 +- (nullable instancetype)init NS_UNAVAILABLE;
116 +
117 +///--------------------------------------------------
118 +/// @name Starting & Stopping Reachability Monitoring
119 +///--------------------------------------------------
120 +
121 +/**
122 + Starts monitoring for changes in network reachability status.
123 + */
124 +- (void)startMonitoring;
125 +
126 +/**
127 + Stops monitoring for changes in network reachability status.
128 + */
129 +- (void)stopMonitoring;
130 +
131 +///-------------------------------------------------
132 +/// @name Getting Localized Reachability Description
133 +///-------------------------------------------------
134 +
135 +/**
136 + Returns a localized string representation of the current network reachability status.
137 + */
138 +- (NSString *)localizedNetworkReachabilityStatusString;
139 +
140 +///---------------------------------------------------
141 +/// @name Setting Network Reachability Change Callback
142 +///---------------------------------------------------
143 +
144 +/**
145 + Sets a callback to be executed when the network availability of the `baseURL` host changes.
146 +
147 + @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`.
148 + */
149 +- (void)setReachabilityStatusChangeBlock:(nullable void (^)(AFNetworkReachabilityStatus status))block;
150 +
151 +@end
152 +
153 +///----------------
154 +/// @name Constants
155 +///----------------
156 +
157 +/**
158 + ## Network Reachability
159 +
160 + The following constants are provided by `AFNetworkReachabilityManager` as possible network reachability statuses.
161 +
162 + enum {
163 + AFNetworkReachabilityStatusUnknown,
164 + AFNetworkReachabilityStatusNotReachable,
165 + AFNetworkReachabilityStatusReachableViaWWAN,
166 + AFNetworkReachabilityStatusReachableViaWiFi,
167 + }
168 +
169 + `AFNetworkReachabilityStatusUnknown`
170 + The `baseURL` host reachability is not known.
171 +
172 + `AFNetworkReachabilityStatusNotReachable`
173 + The `baseURL` host cannot be reached.
174 +
175 + `AFNetworkReachabilityStatusReachableViaWWAN`
176 + The `baseURL` host can be reached via a cellular connection, such as EDGE or GPRS.
177 +
178 + `AFNetworkReachabilityStatusReachableViaWiFi`
179 + The `baseURL` host can be reached via a Wi-Fi connection.
180 +
181 + ### Keys for Notification UserInfo Dictionary
182 +
183 + Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification.
184 +
185 + `AFNetworkingReachabilityNotificationStatusItem`
186 + A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification.
187 + The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status.
188 + */
189 +
190 +///--------------------
191 +/// @name Notifications
192 +///--------------------
193 +
194 +/**
195 + Posted when network reachability changes.
196 + 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.
197 +
198 + @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`).
199 + */
200 +FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityDidChangeNotification;
201 +FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityNotificationStatusItem;
202 +
203 +///--------------------
204 +/// @name Functions
205 +///--------------------
206 +
207 +/**
208 + Returns a localized string representation of an `AFNetworkReachabilityStatus` value.
209 + */
210 +FOUNDATION_EXPORT NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status);
211 +
212 +NS_ASSUME_NONNULL_END
213 +#endif
1 +// AFNetworkReachabilityManager.m
2 +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 +//
4 +// Permission is hereby granted, free of charge, to any person obtaining a copy
5 +// of this software and associated documentation files (the "Software"), to deal
6 +// in the Software without restriction, including without limitation the rights
7 +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 +// copies of the Software, and to permit persons to whom the Software is
9 +// furnished to do so, subject to the following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included in
12 +// all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 +// THE SOFTWARE.
21 +
22 +#import "AFNetworkReachabilityManager.h"
23 +#if !TARGET_OS_WATCH
24 +
25 +#import <netinet/in.h>
26 +#import <netinet6/in6.h>
27 +#import <arpa/inet.h>
28 +#import <ifaddrs.h>
29 +#import <netdb.h>
30 +
31 +NSString * const AFNetworkingReachabilityDidChangeNotification = @"com.alamofire.networking.reachability.change";
32 +NSString * const AFNetworkingReachabilityNotificationStatusItem = @"AFNetworkingReachabilityNotificationStatusItem";
33 +
34 +typedef void (^AFNetworkReachabilityStatusBlock)(AFNetworkReachabilityStatus status);
35 +
36 +NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status) {
37 + switch (status) {
38 + case AFNetworkReachabilityStatusNotReachable:
39 + return NSLocalizedStringFromTable(@"Not Reachable", @"AFNetworking", nil);
40 + case AFNetworkReachabilityStatusReachableViaWWAN:
41 + return NSLocalizedStringFromTable(@"Reachable via WWAN", @"AFNetworking", nil);
42 + case AFNetworkReachabilityStatusReachableViaWiFi:
43 + return NSLocalizedStringFromTable(@"Reachable via WiFi", @"AFNetworking", nil);
44 + case AFNetworkReachabilityStatusUnknown:
45 + default:
46 + return NSLocalizedStringFromTable(@"Unknown", @"AFNetworking", nil);
47 + }
48 +}
49 +
50 +static AFNetworkReachabilityStatus AFNetworkReachabilityStatusForFlags(SCNetworkReachabilityFlags flags) {
51 + BOOL isReachable = ((flags & kSCNetworkReachabilityFlagsReachable) != 0);
52 + BOOL needsConnection = ((flags & kSCNetworkReachabilityFlagsConnectionRequired) != 0);
53 + BOOL canConnectionAutomatically = (((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) || ((flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0));
54 + BOOL canConnectWithoutUserInteraction = (canConnectionAutomatically && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0);
55 + BOOL isNetworkReachable = (isReachable && (!needsConnection || canConnectWithoutUserInteraction));
56 +
57 + AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusUnknown;
58 + if (isNetworkReachable == NO) {
59 + status = AFNetworkReachabilityStatusNotReachable;
60 + }
61 +#if TARGET_OS_IPHONE
62 + else if ((flags & kSCNetworkReachabilityFlagsIsWWAN) != 0) {
63 + status = AFNetworkReachabilityStatusReachableViaWWAN;
64 + }
65 +#endif
66 + else {
67 + status = AFNetworkReachabilityStatusReachableViaWiFi;
68 + }
69 +
70 + return status;
71 +}
72 +
73 +/**
74 + * Queue a status change notification for the main thread.
75 + *
76 + * This is done to ensure that the notifications are received in the same order
77 + * as they are sent. If notifications are sent directly, it is possible that
78 + * a queued notification (for an earlier status condition) is processed after
79 + * the later update, resulting in the listener being left in the wrong state.
80 + */
81 +static void AFPostReachabilityStatusChange(SCNetworkReachabilityFlags flags, AFNetworkReachabilityStatusBlock block) {
82 + AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags);
83 + dispatch_async(dispatch_get_main_queue(), ^{
84 + if (block) {
85 + block(status);
86 + }
87 + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
88 + NSDictionary *userInfo = @{ AFNetworkingReachabilityNotificationStatusItem: @(status) };
89 + [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:userInfo];
90 + });
91 +}
92 +
93 +static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) {
94 + AFPostReachabilityStatusChange(flags, (__bridge AFNetworkReachabilityStatusBlock)info);
95 +}
96 +
97 +
98 +static const void * AFNetworkReachabilityRetainCallback(const void *info) {
99 + return Block_copy(info);
100 +}
101 +
102 +static void AFNetworkReachabilityReleaseCallback(const void *info) {
103 + if (info) {
104 + Block_release(info);
105 + }
106 +}
107 +
108 +@interface AFNetworkReachabilityManager ()
109 +@property (readonly, nonatomic, assign) SCNetworkReachabilityRef networkReachability;
110 +@property (readwrite, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;
111 +@property (readwrite, nonatomic, copy) AFNetworkReachabilityStatusBlock networkReachabilityStatusBlock;
112 +@end
113 +
114 +@implementation AFNetworkReachabilityManager
115 +
116 ++ (instancetype)sharedManager {
117 + static AFNetworkReachabilityManager *_sharedManager = nil;
118 + static dispatch_once_t onceToken;
119 + dispatch_once(&onceToken, ^{
120 + _sharedManager = [self manager];
121 + });
122 +
123 + return _sharedManager;
124 +}
125 +
126 ++ (instancetype)managerForDomain:(NSString *)domain {
127 + SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [domain UTF8String]);
128 +
129 + AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability];
130 +
131 + CFRelease(reachability);
132 +
133 + return manager;
134 +}
135 +
136 ++ (instancetype)managerForAddress:(const void *)address {
137 + SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)address);
138 + AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability];
139 +
140 + CFRelease(reachability);
141 +
142 + return manager;
143 +}
144 +
145 ++ (instancetype)manager
146 +{
147 +#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)
148 + struct sockaddr_in6 address;
149 + bzero(&address, sizeof(address));
150 + address.sin6_len = sizeof(address);
151 + address.sin6_family = AF_INET6;
152 +#else
153 + struct sockaddr_in address;
154 + bzero(&address, sizeof(address));
155 + address.sin_len = sizeof(address);
156 + address.sin_family = AF_INET;
157 +#endif
158 + return [self managerForAddress:&address];
159 +}
160 +
161 +- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability {
162 + self = [super init];
163 + if (!self) {
164 + return nil;
165 + }
166 +
167 + _networkReachability = CFRetain(reachability);
168 + self.networkReachabilityStatus = AFNetworkReachabilityStatusUnknown;
169 +
170 + return self;
171 +}
172 +
173 +- (instancetype)init NS_UNAVAILABLE
174 +{
175 + return nil;
176 +}
177 +
178 +- (void)dealloc {
179 + [self stopMonitoring];
180 +
181 + if (_networkReachability != NULL) {
182 + CFRelease(_networkReachability);
183 + }
184 +}
185 +
186 +#pragma mark -
187 +
188 +- (BOOL)isReachable {
189 + return [self isReachableViaWWAN] || [self isReachableViaWiFi];
190 +}
191 +
192 +- (BOOL)isReachableViaWWAN {
193 + return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN;
194 +}
195 +
196 +- (BOOL)isReachableViaWiFi {
197 + return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi;
198 +}
199 +
200 +#pragma mark -
201 +
202 +- (void)startMonitoring {
203 + [self stopMonitoring];
204 +
205 + if (!self.networkReachability) {
206 + return;
207 + }
208 +
209 + __weak __typeof(self)weakSelf = self;
210 + AFNetworkReachabilityStatusBlock callback = ^(AFNetworkReachabilityStatus status) {
211 + __strong __typeof(weakSelf)strongSelf = weakSelf;
212 +
213 + strongSelf.networkReachabilityStatus = status;
214 + if (strongSelf.networkReachabilityStatusBlock) {
215 + strongSelf.networkReachabilityStatusBlock(status);
216 + }
217 +
218 + };
219 +
220 + SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL};
221 + SCNetworkReachabilitySetCallback(self.networkReachability, AFNetworkReachabilityCallback, &context);
222 + SCNetworkReachabilityScheduleWithRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes);
223 +
224 + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^{
225 + SCNetworkReachabilityFlags flags;
226 + if (SCNetworkReachabilityGetFlags(self.networkReachability, &flags)) {
227 + AFPostReachabilityStatusChange(flags, callback);
228 + }
229 + });
230 +}
231 +
232 +- (void)stopMonitoring {
233 + if (!self.networkReachability) {
234 + return;
235 + }
236 +
237 + SCNetworkReachabilityUnscheduleFromRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes);
238 +}
239 +
240 +#pragma mark -
241 +
242 +- (NSString *)localizedNetworkReachabilityStatusString {
243 + return AFStringFromNetworkReachabilityStatus(self.networkReachabilityStatus);
244 +}
245 +
246 +#pragma mark -
247 +
248 +- (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block {
249 + self.networkReachabilityStatusBlock = block;
250 +}
251 +
252 +#pragma mark - NSKeyValueObserving
253 +
254 ++ (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key {
255 + if ([key isEqualToString:@"reachable"] || [key isEqualToString:@"reachableViaWWAN"] || [key isEqualToString:@"reachableViaWiFi"]) {
256 + return [NSSet setWithObject:@"networkReachabilityStatus"];
257 + }
258 +
259 + return [super keyPathsForValuesAffectingValueForKey:key];
260 +}
261 +
262 +@end
263 +#endif
1 +// AFNetworking.h
2 +//
3 +// Copyright (c) 2013 AFNetworking (http://afnetworking.com/)
4 +//
5 +// Permission is hereby granted, free of charge, to any person obtaining a copy
6 +// of this software and associated documentation files (the "Software"), to deal
7 +// in the Software without restriction, including without limitation the rights
8 +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 +// copies of the Software, and to permit persons to whom the Software is
10 +// furnished to do so, subject to the following conditions:
11 +//
12 +// The above copyright notice and this permission notice shall be included in
13 +// all copies or substantial portions of the Software.
14 +//
15 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 +// THE SOFTWARE.
22 +
23 +#import <Foundation/Foundation.h>
24 +#import <Availability.h>
25 +#import <TargetConditionals.h>
26 +
27 +#ifndef _AFNETWORKING_
28 + #define _AFNETWORKING_
29 +
30 + #import "AFURLRequestSerialization.h"
31 + #import "AFURLResponseSerialization.h"
32 + #import "AFSecurityPolicy.h"
33 +
34 +#if !TARGET_OS_WATCH
35 + #import "AFNetworkReachabilityManager.h"
36 +#endif
37 +
38 + #import "AFURLSessionManager.h"
39 + #import "AFHTTPSessionManager.h"
40 +
41 +#endif /* _AFNETWORKING_ */
1 +// AFSecurityPolicy.h
2 +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 +//
4 +// Permission is hereby granted, free of charge, to any person obtaining a copy
5 +// of this software and associated documentation files (the "Software"), to deal
6 +// in the Software without restriction, including without limitation the rights
7 +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 +// copies of the Software, and to permit persons to whom the Software is
9 +// furnished to do so, subject to the following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included in
12 +// all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 +// THE SOFTWARE.
21 +
22 +#import <Foundation/Foundation.h>
23 +#import <Security/Security.h>
24 +
25 +typedef NS_ENUM(NSUInteger, AFSSLPinningMode) {
26 + AFSSLPinningModeNone,
27 + AFSSLPinningModePublicKey,
28 + AFSSLPinningModeCertificate,
29 +};
30 +
31 +/**
32 + `AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections.
33 +
34 + 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.
35 + */
36 +
37 +NS_ASSUME_NONNULL_BEGIN
38 +
39 +@interface AFSecurityPolicy : NSObject <NSSecureCoding, NSCopying>
40 +
41 +/**
42 + The criteria by which server trust should be evaluated against the pinned SSL certificates. Defaults to `AFSSLPinningModeNone`.
43 + */
44 +@property (readonly, nonatomic, assign) AFSSLPinningMode SSLPinningMode;
45 +
46 +/**
47 + The certificates used to evaluate server trust according to the SSL pinning mode.
48 +
49 + 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`.
50 +
51 + Note that if pinning is enabled, `evaluateServerTrust:forDomain:` will return true if any pinned certificate matches.
52 + */
53 +@property (nonatomic, strong, nullable) NSSet <NSData *> *pinnedCertificates;
54 +
55 +/**
56 + Whether or not to trust servers with an invalid or expired SSL certificates. Defaults to `NO`.
57 + */
58 +@property (nonatomic, assign) BOOL allowInvalidCertificates;
59 +
60 +/**
61 + Whether or not to validate the domain name in the certificate's CN field. Defaults to `YES`.
62 + */
63 +@property (nonatomic, assign) BOOL validatesDomainName;
64 +
65 +///-----------------------------------------
66 +/// @name Getting Certificates from the Bundle
67 +///-----------------------------------------
68 +
69 +/**
70 + 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`.
71 +
72 + @return The certificates included in the given bundle.
73 + */
74 ++ (NSSet <NSData *> *)certificatesInBundle:(NSBundle *)bundle;
75 +
76 +///-----------------------------------------
77 +/// @name Getting Specific Security Policies
78 +///-----------------------------------------
79 +
80 +/**
81 + 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.
82 +
83 + @return The default security policy.
84 + */
85 ++ (instancetype)defaultPolicy;
86 +
87 +///---------------------
88 +/// @name Initialization
89 +///---------------------
90 +
91 +/**
92 + Creates and returns a security policy with the specified pinning mode.
93 +
94 + @param pinningMode The SSL pinning mode.
95 +
96 + @return A new security policy.
97 + */
98 ++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode;
99 +
100 +/**
101 + Creates and returns a security policy with the specified pinning mode.
102 +
103 + @param pinningMode The SSL pinning mode.
104 + @param pinnedCertificates The certificates to pin against.
105 +
106 + @return A new security policy.
107 + */
108 ++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet <NSData *> *)pinnedCertificates;
109 +
110 +///------------------------------
111 +/// @name Evaluating Server Trust
112 +///------------------------------
113 +
114 +/**
115 + Whether or not the specified server trust should be accepted, based on the security policy.
116 +
117 + This method should be used when responding to an authentication challenge from a server.
118 +
119 + @param serverTrust The X.509 certificate trust of the server.
120 + @param domain The domain of serverTrust. If `nil`, the domain will not be validated.
121 +
122 + @return Whether or not to trust the server.
123 + */
124 +- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust
125 + forDomain:(nullable NSString *)domain;
126 +
127 +@end
128 +
129 +NS_ASSUME_NONNULL_END
130 +
131 +///----------------
132 +/// @name Constants
133 +///----------------
134 +
135 +/**
136 + ## SSL Pinning Modes
137 +
138 + The following constants are provided by `AFSSLPinningMode` as possible SSL pinning modes.
139 +
140 + enum {
141 + AFSSLPinningModeNone,
142 + AFSSLPinningModePublicKey,
143 + AFSSLPinningModeCertificate,
144 + }
145 +
146 + `AFSSLPinningModeNone`
147 + Do not used pinned certificates to validate servers.
148 +
149 + `AFSSLPinningModePublicKey`
150 + Validate host certificates against public keys of pinned certificates.
151 +
152 + `AFSSLPinningModeCertificate`
153 + Validate host certificates against pinned certificates.
154 +*/
1 +// AFSecurityPolicy.m
2 +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 +//
4 +// Permission is hereby granted, free of charge, to any person obtaining a copy
5 +// of this software and associated documentation files (the "Software"), to deal
6 +// in the Software without restriction, including without limitation the rights
7 +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 +// copies of the Software, and to permit persons to whom the Software is
9 +// furnished to do so, subject to the following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included in
12 +// all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 +// THE SOFTWARE.
21 +
22 +#import "AFSecurityPolicy.h"
23 +
24 +#import <AssertMacros.h>
25 +
26 +#if !TARGET_OS_IOS && !TARGET_OS_WATCH && !TARGET_OS_TV
27 +static NSData * AFSecKeyGetData(SecKeyRef key) {
28 + CFDataRef data = NULL;
29 +
30 + __Require_noErr_Quiet(SecItemExport(key, kSecFormatUnknown, kSecItemPemArmour, NULL, &data), _out);
31 +
32 + return (__bridge_transfer NSData *)data;
33 +
34 +_out:
35 + if (data) {
36 + CFRelease(data);
37 + }
38 +
39 + return nil;
40 +}
41 +#endif
42 +
43 +static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
44 +#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV
45 + return [(__bridge id)key1 isEqual:(__bridge id)key2];
46 +#else
47 + return [AFSecKeyGetData(key1) isEqual:AFSecKeyGetData(key2)];
48 +#endif
49 +}
50 +
51 +static id AFPublicKeyForCertificate(NSData *certificate) {
52 + id allowedPublicKey = nil;
53 + SecCertificateRef allowedCertificate;
54 + SecPolicyRef policy = nil;
55 + SecTrustRef allowedTrust = nil;
56 + SecTrustResultType result;
57 +
58 + allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificate);
59 + __Require_Quiet(allowedCertificate != NULL, _out);
60 +
61 + policy = SecPolicyCreateBasicX509();
62 + __Require_noErr_Quiet(SecTrustCreateWithCertificates(allowedCertificate, policy, &allowedTrust), _out);
63 + __Require_noErr_Quiet(SecTrustEvaluate(allowedTrust, &result), _out);
64 +
65 + allowedPublicKey = (__bridge_transfer id)SecTrustCopyPublicKey(allowedTrust);
66 +
67 +_out:
68 + if (allowedTrust) {
69 + CFRelease(allowedTrust);
70 + }
71 +
72 + if (policy) {
73 + CFRelease(policy);
74 + }
75 +
76 + if (allowedCertificate) {
77 + CFRelease(allowedCertificate);
78 + }
79 +
80 + return allowedPublicKey;
81 +}
82 +
83 +static BOOL AFServerTrustIsValid(SecTrustRef serverTrust) {
84 + BOOL isValid = NO;
85 + SecTrustResultType result;
86 + __Require_noErr_Quiet(SecTrustEvaluate(serverTrust, &result), _out);
87 +
88 + isValid = (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed);
89 +
90 +_out:
91 + return isValid;
92 +}
93 +
94 +static NSArray * AFCertificateTrustChainForServerTrust(SecTrustRef serverTrust) {
95 + CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust);
96 + NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount];
97 +
98 + for (CFIndex i = 0; i < certificateCount; i++) {
99 + SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i);
100 + [trustChain addObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)];
101 + }
102 +
103 + return [NSArray arrayWithArray:trustChain];
104 +}
105 +
106 +static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) {
107 + SecPolicyRef policy = SecPolicyCreateBasicX509();
108 + CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust);
109 + NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount];
110 + for (CFIndex i = 0; i < certificateCount; i++) {
111 + SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i);
112 +
113 + SecCertificateRef someCertificates[] = {certificate};
114 + CFArrayRef certificates = CFArrayCreate(NULL, (const void **)someCertificates, 1, NULL);
115 +
116 + SecTrustRef trust;
117 + __Require_noErr_Quiet(SecTrustCreateWithCertificates(certificates, policy, &trust), _out);
118 +
119 + SecTrustResultType result;
120 + __Require_noErr_Quiet(SecTrustEvaluate(trust, &result), _out);
121 +
122 + [trustChain addObject:(__bridge_transfer id)SecTrustCopyPublicKey(trust)];
123 +
124 + _out:
125 + if (trust) {
126 + CFRelease(trust);
127 + }
128 +
129 + if (certificates) {
130 + CFRelease(certificates);
131 + }
132 +
133 + continue;
134 + }
135 + CFRelease(policy);
136 +
137 + return [NSArray arrayWithArray:trustChain];
138 +}
139 +
140 +#pragma mark -
141 +
142 +@interface AFSecurityPolicy()
143 +@property (readwrite, nonatomic, assign) AFSSLPinningMode SSLPinningMode;
144 +@property (readwrite, nonatomic, strong) NSSet *pinnedPublicKeys;
145 +@end
146 +
147 +@implementation AFSecurityPolicy
148 +
149 ++ (NSSet *)certificatesInBundle:(NSBundle *)bundle {
150 + NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."];
151 +
152 + NSMutableSet *certificates = [NSMutableSet setWithCapacity:[paths count]];
153 + for (NSString *path in paths) {
154 + NSData *certificateData = [NSData dataWithContentsOfFile:path];
155 + [certificates addObject:certificateData];
156 + }
157 +
158 + return [NSSet setWithSet:certificates];
159 +}
160 +
161 ++ (NSSet *)defaultPinnedCertificates {
162 + static NSSet *_defaultPinnedCertificates = nil;
163 + static dispatch_once_t onceToken;
164 + dispatch_once(&onceToken, ^{
165 + NSBundle *bundle = [NSBundle bundleForClass:[self class]];
166 + _defaultPinnedCertificates = [self certificatesInBundle:bundle];
167 + });
168 +
169 + return _defaultPinnedCertificates;
170 +}
171 +
172 ++ (instancetype)defaultPolicy {
173 + AFSecurityPolicy *securityPolicy = [[self alloc] init];
174 + securityPolicy.SSLPinningMode = AFSSLPinningModeNone;
175 +
176 + return securityPolicy;
177 +}
178 +
179 ++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode {
180 + return [self policyWithPinningMode:pinningMode withPinnedCertificates:[self defaultPinnedCertificates]];
181 +}
182 +
183 ++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet *)pinnedCertificates {
184 + AFSecurityPolicy *securityPolicy = [[self alloc] init];
185 + securityPolicy.SSLPinningMode = pinningMode;
186 +
187 + [securityPolicy setPinnedCertificates:pinnedCertificates];
188 +
189 + return securityPolicy;
190 +}
191 +
192 +- (instancetype)init {
193 + self = [super init];
194 + if (!self) {
195 + return nil;
196 + }
197 +
198 + self.validatesDomainName = YES;
199 +
200 + return self;
201 +}
202 +
203 +- (void)setPinnedCertificates:(NSSet *)pinnedCertificates {
204 + _pinnedCertificates = pinnedCertificates;
205 +
206 + if (self.pinnedCertificates) {
207 + NSMutableSet *mutablePinnedPublicKeys = [NSMutableSet setWithCapacity:[self.pinnedCertificates count]];
208 + for (NSData *certificate in self.pinnedCertificates) {
209 + id publicKey = AFPublicKeyForCertificate(certificate);
210 + if (!publicKey) {
211 + continue;
212 + }
213 + [mutablePinnedPublicKeys addObject:publicKey];
214 + }
215 + self.pinnedPublicKeys = [NSSet setWithSet:mutablePinnedPublicKeys];
216 + } else {
217 + self.pinnedPublicKeys = nil;
218 + }
219 +}
220 +
221 +#pragma mark -
222 +
223 +- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust
224 + forDomain:(NSString *)domain
225 +{
226 + if (domain && self.allowInvalidCertificates && self.validatesDomainName && (self.SSLPinningMode == AFSSLPinningModeNone || [self.pinnedCertificates count] == 0)) {
227 + // https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/NetworkingTopics/Articles/OverridingSSLChainValidationCorrectly.html
228 + // According to the docs, you should only trust your provided certs for evaluation.
229 + // Pinned certificates are added to the trust. Without pinned certificates,
230 + // there is nothing to evaluate against.
231 + //
232 + // From Apple Docs:
233 + // "Do not implicitly trust self-signed certificates as anchors (kSecTrustOptionImplicitAnchors).
234 + // Instead, add your own (self-signed) CA certificate to the list of trusted anchors."
235 + NSLog(@"In order to validate a domain name for self signed certificates, you MUST use pinning.");
236 + return NO;
237 + }
238 +
239 + NSMutableArray *policies = [NSMutableArray array];
240 + if (self.validatesDomainName) {
241 + [policies addObject:(__bridge_transfer id)SecPolicyCreateSSL(true, (__bridge CFStringRef)domain)];
242 + } else {
243 + [policies addObject:(__bridge_transfer id)SecPolicyCreateBasicX509()];
244 + }
245 +
246 + SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies);
247 +
248 + if (self.SSLPinningMode == AFSSLPinningModeNone) {
249 + return self.allowInvalidCertificates || AFServerTrustIsValid(serverTrust);
250 + } else if (!AFServerTrustIsValid(serverTrust) && !self.allowInvalidCertificates) {
251 + return NO;
252 + }
253 +
254 + switch (self.SSLPinningMode) {
255 + case AFSSLPinningModeNone:
256 + default:
257 + return NO;
258 + case AFSSLPinningModeCertificate: {
259 + NSMutableArray *pinnedCertificates = [NSMutableArray array];
260 + for (NSData *certificateData in self.pinnedCertificates) {
261 + [pinnedCertificates addObject:(__bridge_transfer id)SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificateData)];
262 + }
263 + SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)pinnedCertificates);
264 +
265 + if (!AFServerTrustIsValid(serverTrust)) {
266 + return NO;
267 + }
268 +
269 + // obtain the chain after being validated, which *should* contain the pinned certificate in the last position (if it's the Root CA)
270 + NSArray *serverCertificates = AFCertificateTrustChainForServerTrust(serverTrust);
271 +
272 + for (NSData *trustChainCertificate in [serverCertificates reverseObjectEnumerator]) {
273 + if ([self.pinnedCertificates containsObject:trustChainCertificate]) {
274 + return YES;
275 + }
276 + }
277 +
278 + return NO;
279 + }
280 + case AFSSLPinningModePublicKey: {
281 + NSUInteger trustedPublicKeyCount = 0;
282 + NSArray *publicKeys = AFPublicKeyTrustChainForServerTrust(serverTrust);
283 +
284 + for (id trustChainPublicKey in publicKeys) {
285 + for (id pinnedPublicKey in self.pinnedPublicKeys) {
286 + if (AFSecKeyIsEqualToKey((__bridge SecKeyRef)trustChainPublicKey, (__bridge SecKeyRef)pinnedPublicKey)) {
287 + trustedPublicKeyCount += 1;
288 + }
289 + }
290 + }
291 + return trustedPublicKeyCount > 0;
292 + }
293 + }
294 +
295 + return NO;
296 +}
297 +
298 +#pragma mark - NSKeyValueObserving
299 +
300 ++ (NSSet *)keyPathsForValuesAffectingPinnedPublicKeys {
301 + return [NSSet setWithObject:@"pinnedCertificates"];
302 +}
303 +
304 +#pragma mark - NSSecureCoding
305 +
306 ++ (BOOL)supportsSecureCoding {
307 + return YES;
308 +}
309 +
310 +- (instancetype)initWithCoder:(NSCoder *)decoder {
311 +
312 + self = [self init];
313 + if (!self) {
314 + return nil;
315 + }
316 +
317 + self.SSLPinningMode = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(SSLPinningMode))] unsignedIntegerValue];
318 + self.allowInvalidCertificates = [decoder decodeBoolForKey:NSStringFromSelector(@selector(allowInvalidCertificates))];
319 + self.validatesDomainName = [decoder decodeBoolForKey:NSStringFromSelector(@selector(validatesDomainName))];
320 + self.pinnedCertificates = [decoder decodeObjectOfClass:[NSArray class] forKey:NSStringFromSelector(@selector(pinnedCertificates))];
321 +
322 + return self;
323 +}
324 +
325 +- (void)encodeWithCoder:(NSCoder *)coder {
326 + [coder encodeObject:[NSNumber numberWithUnsignedInteger:self.SSLPinningMode] forKey:NSStringFromSelector(@selector(SSLPinningMode))];
327 + [coder encodeBool:self.allowInvalidCertificates forKey:NSStringFromSelector(@selector(allowInvalidCertificates))];
328 + [coder encodeBool:self.validatesDomainName forKey:NSStringFromSelector(@selector(validatesDomainName))];
329 + [coder encodeObject:self.pinnedCertificates forKey:NSStringFromSelector(@selector(pinnedCertificates))];
330 +}
331 +
332 +#pragma mark - NSCopying
333 +
334 +- (instancetype)copyWithZone:(NSZone *)zone {
335 + AFSecurityPolicy *securityPolicy = [[[self class] allocWithZone:zone] init];
336 + securityPolicy.SSLPinningMode = self.SSLPinningMode;
337 + securityPolicy.allowInvalidCertificates = self.allowInvalidCertificates;
338 + securityPolicy.validatesDomainName = self.validatesDomainName;
339 + securityPolicy.pinnedCertificates = [self.pinnedCertificates copyWithZone:zone];
340 +
341 + return securityPolicy;
342 +}
343 +
344 +@end
1 +// AFURLRequestSerialization.h
2 +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 +//
4 +// Permission is hereby granted, free of charge, to any person obtaining a copy
5 +// of this software and associated documentation files (the "Software"), to deal
6 +// in the Software without restriction, including without limitation the rights
7 +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 +// copies of the Software, and to permit persons to whom the Software is
9 +// furnished to do so, subject to the following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included in
12 +// all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 +// THE SOFTWARE.
21 +
22 +#import <Foundation/Foundation.h>
23 +#import <TargetConditionals.h>
24 +
25 +#if TARGET_OS_IOS || TARGET_OS_TV
26 +#import <UIKit/UIKit.h>
27 +#elif TARGET_OS_WATCH
28 +#import <WatchKit/WatchKit.h>
29 +#endif
30 +
31 +NS_ASSUME_NONNULL_BEGIN
32 +
33 +/**
34 + Returns a percent-escaped string following RFC 3986 for a query string key or value.
35 + RFC 3986 states that the following characters are "reserved" characters.
36 + - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
37 + - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
38 +
39 + In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
40 + query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
41 + should be percent-escaped in the query string.
42 +
43 + @param string The string to be percent-escaped.
44 +
45 + @return The percent-escaped string.
46 + */
47 +FOUNDATION_EXPORT NSString * AFPercentEscapedStringFromString(NSString *string);
48 +
49 +/**
50 + A helper method to generate encoded url query parameters for appending to the end of a URL.
51 +
52 + @param parameters A dictionary of key/values to be encoded.
53 +
54 + @return A url encoded query string
55 + */
56 +FOUNDATION_EXPORT NSString * AFQueryStringFromParameters(NSDictionary *parameters);
57 +
58 +/**
59 + 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.
60 +
61 + 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`.
62 + */
63 +@protocol AFURLRequestSerialization <NSObject, NSSecureCoding, NSCopying>
64 +
65 +/**
66 + Returns a request with the specified parameters encoded into a copy of the original request.
67 +
68 + @param request The original request.
69 + @param parameters The parameters to be encoded.
70 + @param error The error that occurred while attempting to encode the request parameters.
71 +
72 + @return A serialized request.
73 + */
74 +- (nullable NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
75 + withParameters:(nullable id)parameters
76 + error:(NSError * _Nullable __autoreleasing *)error NS_SWIFT_NOTHROW;
77 +
78 +@end
79 +
80 +#pragma mark -
81 +
82 +/**
83 +
84 + */
85 +typedef NS_ENUM(NSUInteger, AFHTTPRequestQueryStringSerializationStyle) {
86 + AFHTTPRequestQueryStringDefaultStyle = 0,
87 +};
88 +
89 +@protocol AFMultipartFormData;
90 +
91 +/**
92 + `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.
93 +
94 + Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPRequestSerializer` in order to ensure consistent default behavior.
95 + */
96 +@interface AFHTTPRequestSerializer : NSObject <AFURLRequestSerialization>
97 +
98 +/**
99 + The string encoding used to serialize parameters. `NSUTF8StringEncoding` by default.
100 + */
101 +@property (nonatomic, assign) NSStringEncoding stringEncoding;
102 +
103 +/**
104 + Whether created requests can use the device’s cellular radio (if present). `YES` by default.
105 +
106 + @see NSMutableURLRequest -setAllowsCellularAccess:
107 + */
108 +@property (nonatomic, assign) BOOL allowsCellularAccess;
109 +
110 +/**
111 + The cache policy of created requests. `NSURLRequestUseProtocolCachePolicy` by default.
112 +
113 + @see NSMutableURLRequest -setCachePolicy:
114 + */
115 +@property (nonatomic, assign) NSURLRequestCachePolicy cachePolicy;
116 +
117 +/**
118 + Whether created requests should use the default cookie handling. `YES` by default.
119 +
120 + @see NSMutableURLRequest -setHTTPShouldHandleCookies:
121 + */
122 +@property (nonatomic, assign) BOOL HTTPShouldHandleCookies;
123 +
124 +/**
125 + Whether created requests can continue transmitting data before receiving a response from an earlier transmission. `NO` by default
126 +
127 + @see NSMutableURLRequest -setHTTPShouldUsePipelining:
128 + */
129 +@property (nonatomic, assign) BOOL HTTPShouldUsePipelining;
130 +
131 +/**
132 + The network service type for created requests. `NSURLNetworkServiceTypeDefault` by default.
133 +
134 + @see NSMutableURLRequest -setNetworkServiceType:
135 + */
136 +@property (nonatomic, assign) NSURLRequestNetworkServiceType networkServiceType;
137 +
138 +/**
139 + The timeout interval, in seconds, for created requests. The default timeout interval is 60 seconds.
140 +
141 + @see NSMutableURLRequest -setTimeoutInterval:
142 + */
143 +@property (nonatomic, assign) NSTimeInterval timeoutInterval;
144 +
145 +///---------------------------------------
146 +/// @name Configuring HTTP Request Headers
147 +///---------------------------------------
148 +
149 +/**
150 + Default HTTP header field values to be applied to serialized requests. By default, these include the following:
151 +
152 + - `Accept-Language` with the contents of `NSLocale +preferredLanguages`
153 + - `User-Agent` with the contents of various bundle identifiers and OS designations
154 +
155 + @discussion To add or remove default request headers, use `setValue:forHTTPHeaderField:`.
156 + */
157 +@property (readonly, nonatomic, strong) NSDictionary <NSString *, NSString *> *HTTPRequestHeaders;
158 +
159 +/**
160 + Creates and returns a serializer with default configuration.
161 + */
162 ++ (instancetype)serializer;
163 +
164 +/**
165 + 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.
166 +
167 + @param field The HTTP header to set a default value for
168 + @param value The value set as default for the specified header, or `nil`
169 + */
170 +- (void)setValue:(nullable NSString *)value
171 +forHTTPHeaderField:(NSString *)field;
172 +
173 +/**
174 + Returns the value for the HTTP headers set in the request serializer.
175 +
176 + @param field The HTTP header to retrieve the default value for
177 +
178 + @return The value set as default for the specified header, or `nil`
179 + */
180 +- (nullable NSString *)valueForHTTPHeaderField:(NSString *)field;
181 +
182 +/**
183 + 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.
184 +
185 + @param username The HTTP basic auth username
186 + @param password The HTTP basic auth password
187 + */
188 +- (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username
189 + password:(NSString *)password;
190 +
191 +/**
192 + Clears any existing value for the "Authorization" HTTP header.
193 + */
194 +- (void)clearAuthorizationHeader;
195 +
196 +///-------------------------------------------------------
197 +/// @name Configuring Query String Parameter Serialization
198 +///-------------------------------------------------------
199 +
200 +/**
201 + HTTP methods for which serialized requests will encode parameters as a query string. `GET`, `HEAD`, and `DELETE` by default.
202 + */
203 +@property (nonatomic, strong) NSSet <NSString *> *HTTPMethodsEncodingParametersInURI;
204 +
205 +/**
206 + Set the method of query string serialization according to one of the pre-defined styles.
207 +
208 + @param style The serialization style.
209 +
210 + @see AFHTTPRequestQueryStringSerializationStyle
211 + */
212 +- (void)setQueryStringSerializationWithStyle:(AFHTTPRequestQueryStringSerializationStyle)style;
213 +
214 +/**
215 + Set the a custom method of query string serialization according to the specified block.
216 +
217 + @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.
218 + */
219 +- (void)setQueryStringSerializationWithBlock:(nullable NSString * (^)(NSURLRequest *request, id parameters, NSError * __autoreleasing *error))block;
220 +
221 +///-------------------------------
222 +/// @name Creating Request Objects
223 +///-------------------------------
224 +
225 +/**
226 + Creates an `NSMutableURLRequest` object with the specified HTTP method and URL string.
227 +
228 + 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.
229 +
230 + @param method The HTTP method for the request, such as `GET`, `POST`, `PUT`, or `DELETE`. This parameter must not be `nil`.
231 + @param URLString The URL string used to create the request URL.
232 + @param parameters The parameters to be either set as a query string for `GET` requests, or the request HTTP body.
233 + @param error The error that occurred while constructing the request.
234 +
235 + @return An `NSMutableURLRequest` object.
236 + */
237 +- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
238 + URLString:(NSString *)URLString
239 + parameters:(nullable id)parameters
240 + error:(NSError * _Nullable __autoreleasing *)error;
241 +
242 +/**
243 + 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
244 +
245 + 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.
246 +
247 + @param method The HTTP method for the request. This parameter must not be `GET` or `HEAD`, or `nil`.
248 + @param URLString The URL string used to create the request URL.
249 + @param parameters The parameters to be encoded and set in the request HTTP body.
250 + @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.
251 + @param error The error that occurred while constructing the request.
252 +
253 + @return An `NSMutableURLRequest` object
254 + */
255 +- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
256 + URLString:(NSString *)URLString
257 + parameters:(nullable NSDictionary <NSString *, id> *)parameters
258 + constructingBodyWithBlock:(nullable void (^)(id <AFMultipartFormData> formData))block
259 + error:(NSError * _Nullable __autoreleasing *)error;
260 +
261 +/**
262 + 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.
263 +
264 + @param request The multipart form request. The `HTTPBodyStream` property of `request` must not be `nil`.
265 + @param fileURL The file URL to write multipart form contents to.
266 + @param handler A handler block to execute.
267 +
268 + @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.
269 +
270 + @see https://github.com/AFNetworking/AFNetworking/issues/1398
271 + */
272 +- (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request
273 + writingStreamContentsToFile:(NSURL *)fileURL
274 + completionHandler:(nullable void (^)(NSError * _Nullable error))handler;
275 +
276 +@end
277 +
278 +#pragma mark -
279 +
280 +/**
281 + The `AFMultipartFormData` protocol defines the methods supported by the parameter in the block argument of `AFHTTPRequestSerializer -multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:`.
282 + */
283 +@protocol AFMultipartFormData
284 +
285 +/**
286 + 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.
287 +
288 + 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.
289 +
290 + @param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`.
291 + @param name The name to be associated with the specified data. This parameter must not be `nil`.
292 + @param error If an error occurs, upon return contains an `NSError` object that describes the problem.
293 +
294 + @return `YES` if the file data was successfully appended, otherwise `NO`.
295 + */
296 +- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
297 + name:(NSString *)name
298 + error:(NSError * _Nullable __autoreleasing *)error;
299 +
300 +/**
301 + 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.
302 +
303 + @param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`.
304 + @param name The name to be associated with the specified data. This parameter must not be `nil`.
305 + @param fileName The file name to be used in the `Content-Disposition` header. This parameter must not be `nil`.
306 + @param mimeType The declared MIME type of the file data. This parameter must not be `nil`.
307 + @param error If an error occurs, upon return contains an `NSError` object that describes the problem.
308 +
309 + @return `YES` if the file data was successfully appended otherwise `NO`.
310 + */
311 +- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
312 + name:(NSString *)name
313 + fileName:(NSString *)fileName
314 + mimeType:(NSString *)mimeType
315 + error:(NSError * _Nullable __autoreleasing *)error;
316 +
317 +/**
318 + 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.
319 +
320 + @param inputStream The input stream to be appended to the form data
321 + @param name The name to be associated with the specified input stream. This parameter must not be `nil`.
322 + @param fileName The filename to be associated with the specified input stream. This parameter must not be `nil`.
323 + @param length The length of the specified input stream in bytes.
324 + @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`.
325 + */
326 +- (void)appendPartWithInputStream:(nullable NSInputStream *)inputStream
327 + name:(NSString *)name
328 + fileName:(NSString *)fileName
329 + length:(int64_t)length
330 + mimeType:(NSString *)mimeType;
331 +
332 +/**
333 + 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.
334 +
335 + @param data The data to be encoded and appended to the form data.
336 + @param name The name to be associated with the specified data. This parameter must not be `nil`.
337 + @param fileName The filename to be associated with the specified data. This parameter must not be `nil`.
338 + @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`.
339 + */
340 +- (void)appendPartWithFileData:(NSData *)data
341 + name:(NSString *)name
342 + fileName:(NSString *)fileName
343 + mimeType:(NSString *)mimeType;
344 +
345 +/**
346 + Appends the HTTP headers `Content-Disposition: form-data; name=#{name}"`, followed by the encoded data and the multipart form boundary.
347 +
348 + @param data The data to be encoded and appended to the form data.
349 + @param name The name to be associated with the specified data. This parameter must not be `nil`.
350 + */
351 +
352 +- (void)appendPartWithFormData:(NSData *)data
353 + name:(NSString *)name;
354 +
355 +
356 +/**
357 + Appends HTTP headers, followed by the encoded data and the multipart form boundary.
358 +
359 + @param headers The HTTP headers to be appended to the form data.
360 + @param body The data to be encoded and appended to the form data. This parameter must not be `nil`.
361 + */
362 +- (void)appendPartWithHeaders:(nullable NSDictionary <NSString *, NSString *> *)headers
363 + body:(NSData *)body;
364 +
365 +/**
366 + Throttles request bandwidth by limiting the packet size and adding a delay for each chunk read from the upload stream.
367 +
368 + 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.
369 +
370 + @param numberOfBytes Maximum packet size, in number of bytes. The default packet size for an input stream is 16kb.
371 + @param delay Duration of delay each time a packet is read. By default, no delay is set.
372 + */
373 +- (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes
374 + delay:(NSTimeInterval)delay;
375 +
376 +@end
377 +
378 +#pragma mark -
379 +
380 +/**
381 + `AFJSONRequestSerializer` is a subclass of `AFHTTPRequestSerializer` that encodes parameters as JSON using `NSJSONSerialization`, setting the `Content-Type` of the encoded request to `application/json`.
382 + */
383 +@interface AFJSONRequestSerializer : AFHTTPRequestSerializer
384 +
385 +/**
386 + Options for writing the request JSON data from Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONWritingOptions". `0` by default.
387 + */
388 +@property (nonatomic, assign) NSJSONWritingOptions writingOptions;
389 +
390 +/**
391 + Creates and returns a JSON serializer with specified reading and writing options.
392 +
393 + @param writingOptions The specified JSON writing options.
394 + */
395 ++ (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions;
396 +
397 +@end
398 +
399 +#pragma mark -
400 +
401 +/**
402 + `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`.
403 + */
404 +@interface AFPropertyListRequestSerializer : AFHTTPRequestSerializer
405 +
406 +/**
407 + The property list format. Possible values are described in "NSPropertyListFormat".
408 + */
409 +@property (nonatomic, assign) NSPropertyListFormat format;
410 +
411 +/**
412 + @warning The `writeOptions` property is currently unused.
413 + */
414 +@property (nonatomic, assign) NSPropertyListWriteOptions writeOptions;
415 +
416 +/**
417 + Creates and returns a property list serializer with a specified format, read options, and write options.
418 +
419 + @param format The property list format.
420 + @param writeOptions The property list write options.
421 +
422 + @warning The `writeOptions` property is currently unused.
423 + */
424 ++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format
425 + writeOptions:(NSPropertyListWriteOptions)writeOptions;
426 +
427 +@end
428 +
429 +#pragma mark -
430 +
431 +///----------------
432 +/// @name Constants
433 +///----------------
434 +
435 +/**
436 + ## Error Domains
437 +
438 + The following error domain is predefined.
439 +
440 + - `NSString * const AFURLRequestSerializationErrorDomain`
441 +
442 + ### Constants
443 +
444 + `AFURLRequestSerializationErrorDomain`
445 + AFURLRequestSerializer errors. Error codes for `AFURLRequestSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`.
446 + */
447 +FOUNDATION_EXPORT NSString * const AFURLRequestSerializationErrorDomain;
448 +
449 +/**
450 + ## User info dictionary keys
451 +
452 + These keys may exist in the user info dictionary, in addition to those defined for NSError.
453 +
454 + - `NSString * const AFNetworkingOperationFailingURLRequestErrorKey`
455 +
456 + ### Constants
457 +
458 + `AFNetworkingOperationFailingURLRequestErrorKey`
459 + The corresponding value is an `NSURLRequest` containing the request of the operation associated with an error. This key is only present in the `AFURLRequestSerializationErrorDomain`.
460 + */
461 +FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLRequestErrorKey;
462 +
463 +/**
464 + ## Throttling Bandwidth for HTTP Request Input Streams
465 +
466 + @see -throttleBandwidthWithPacketSize:delay:
467 +
468 + ### Constants
469 +
470 + `kAFUploadStream3GSuggestedPacketSize`
471 + Maximum packet size, in number of bytes. Equal to 16kb.
472 +
473 + `kAFUploadStream3GSuggestedDelay`
474 + Duration of delay each time a packet is read. Equal to 0.2 seconds.
475 + */
476 +FOUNDATION_EXPORT NSUInteger const kAFUploadStream3GSuggestedPacketSize;
477 +FOUNDATION_EXPORT NSTimeInterval const kAFUploadStream3GSuggestedDelay;
478 +
479 +NS_ASSUME_NONNULL_END
1 +// AFURLRequestSerialization.m
2 +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 +//
4 +// Permission is hereby granted, free of charge, to any person obtaining a copy
5 +// of this software and associated documentation files (the "Software"), to deal
6 +// in the Software without restriction, including without limitation the rights
7 +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 +// copies of the Software, and to permit persons to whom the Software is
9 +// furnished to do so, subject to the following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included in
12 +// all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 +// THE SOFTWARE.
21 +
22 +#import "AFURLRequestSerialization.h"
23 +
24 +#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV
25 +#import <MobileCoreServices/MobileCoreServices.h>
26 +#else
27 +#import <CoreServices/CoreServices.h>
28 +#endif
29 +
30 +NSString * const AFURLRequestSerializationErrorDomain = @"com.alamofire.error.serialization.request";
31 +NSString * const AFNetworkingOperationFailingURLRequestErrorKey = @"com.alamofire.serialization.request.error.response";
32 +
33 +typedef NSString * (^AFQueryStringSerializationBlock)(NSURLRequest *request, id parameters, NSError *__autoreleasing *error);
34 +
35 +/**
36 + Returns a percent-escaped string following RFC 3986 for a query string key or value.
37 + RFC 3986 states that the following characters are "reserved" characters.
38 + - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
39 + - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
40 +
41 + In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
42 + query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
43 + should be percent-escaped in the query string.
44 + - parameter string: The string to be percent-escaped.
45 + - returns: The percent-escaped string.
46 + */
47 +NSString * AFPercentEscapedStringFromString(NSString *string) {
48 + static NSString * const kAFCharactersGeneralDelimitersToEncode = @":#[]@"; // does not include "?" or "/" due to RFC 3986 - Section 3.4
49 + static NSString * const kAFCharactersSubDelimitersToEncode = @"!$&'()*+,;=";
50 +
51 + NSMutableCharacterSet * allowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
52 + [allowedCharacterSet removeCharactersInString:[kAFCharactersGeneralDelimitersToEncode stringByAppendingString:kAFCharactersSubDelimitersToEncode]];
53 +
54 + // FIXME: https://github.com/AFNetworking/AFNetworking/pull/3028
55 + // return [string stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet];
56 +
57 + static NSUInteger const batchSize = 50;
58 +
59 + NSUInteger index = 0;
60 + NSMutableString *escaped = @"".mutableCopy;
61 +
62 + while (index < string.length) {
63 + NSUInteger length = MIN(string.length - index, batchSize);
64 + NSRange range = NSMakeRange(index, length);
65 +
66 + // To avoid breaking up character sequences such as 👴🏻👮🏽
67 + range = [string rangeOfComposedCharacterSequencesForRange:range];
68 +
69 + NSString *substring = [string substringWithRange:range];
70 + NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet];
71 + [escaped appendString:encoded];
72 +
73 + index += range.length;
74 + }
75 +
76 + return escaped;
77 +}
78 +
79 +#pragma mark -
80 +
81 +@interface AFQueryStringPair : NSObject
82 +@property (readwrite, nonatomic, strong) id field;
83 +@property (readwrite, nonatomic, strong) id value;
84 +
85 +- (instancetype)initWithField:(id)field value:(id)value;
86 +
87 +- (NSString *)URLEncodedStringValue;
88 +@end
89 +
90 +@implementation AFQueryStringPair
91 +
92 +- (instancetype)initWithField:(id)field value:(id)value {
93 + self = [super init];
94 + if (!self) {
95 + return nil;
96 + }
97 +
98 + self.field = field;
99 + self.value = value;
100 +
101 + return self;
102 +}
103 +
104 +- (NSString *)URLEncodedStringValue {
105 + if (!self.value || [self.value isEqual:[NSNull null]]) {
106 + return AFPercentEscapedStringFromString([self.field description]);
107 + } else {
108 + return [NSString stringWithFormat:@"%@=%@", AFPercentEscapedStringFromString([self.field description]), AFPercentEscapedStringFromString([self.value description])];
109 + }
110 +}
111 +
112 +@end
113 +
114 +#pragma mark -
115 +
116 +FOUNDATION_EXPORT NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary);
117 +FOUNDATION_EXPORT NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value);
118 +
119 +NSString * AFQueryStringFromParameters(NSDictionary *parameters) {
120 + NSMutableArray *mutablePairs = [NSMutableArray array];
121 + for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) {
122 + [mutablePairs addObject:[pair URLEncodedStringValue]];
123 + }
124 +
125 + return [mutablePairs componentsJoinedByString:@"&"];
126 +}
127 +
128 +NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary) {
129 + return AFQueryStringPairsFromKeyAndValue(nil, dictionary);
130 +}
131 +
132 +NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value) {
133 + NSMutableArray *mutableQueryStringComponents = [NSMutableArray array];
134 +
135 + NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES selector:@selector(compare:)];
136 +
137 + if ([value isKindOfClass:[NSDictionary class]]) {
138 + NSDictionary *dictionary = value;
139 + // Sort dictionary keys to ensure consistent ordering in query string, which is important when deserializing potentially ambiguous sequences, such as an array of dictionaries
140 + for (id nestedKey in [dictionary.allKeys sortedArrayUsingDescriptors:@[ sortDescriptor ]]) {
141 + id nestedValue = dictionary[nestedKey];
142 + if (nestedValue) {
143 + [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue((key ? [NSString stringWithFormat:@"%@[%@]", key, nestedKey] : nestedKey), nestedValue)];
144 + }
145 + }
146 + } else if ([value isKindOfClass:[NSArray class]]) {
147 + NSArray *array = value;
148 + for (id nestedValue in array) {
149 + [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue([NSString stringWithFormat:@"%@[]", key], nestedValue)];
150 + }
151 + } else if ([value isKindOfClass:[NSSet class]]) {
152 + NSSet *set = value;
153 + for (id obj in [set sortedArrayUsingDescriptors:@[ sortDescriptor ]]) {
154 + [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue(key, obj)];
155 + }
156 + } else {
157 + [mutableQueryStringComponents addObject:[[AFQueryStringPair alloc] initWithField:key value:value]];
158 + }
159 +
160 + return mutableQueryStringComponents;
161 +}
162 +
163 +#pragma mark -
164 +
165 +@interface AFStreamingMultipartFormData : NSObject <AFMultipartFormData>
166 +- (instancetype)initWithURLRequest:(NSMutableURLRequest *)urlRequest
167 + stringEncoding:(NSStringEncoding)encoding;
168 +
169 +- (NSMutableURLRequest *)requestByFinalizingMultipartFormData;
170 +@end
171 +
172 +#pragma mark -
173 +
174 +static NSArray * AFHTTPRequestSerializerObservedKeyPaths() {
175 + static NSArray *_AFHTTPRequestSerializerObservedKeyPaths = nil;
176 + static dispatch_once_t onceToken;
177 + dispatch_once(&onceToken, ^{
178 + _AFHTTPRequestSerializerObservedKeyPaths = @[NSStringFromSelector(@selector(allowsCellularAccess)), NSStringFromSelector(@selector(cachePolicy)), NSStringFromSelector(@selector(HTTPShouldHandleCookies)), NSStringFromSelector(@selector(HTTPShouldUsePipelining)), NSStringFromSelector(@selector(networkServiceType)), NSStringFromSelector(@selector(timeoutInterval))];
179 + });
180 +
181 + return _AFHTTPRequestSerializerObservedKeyPaths;
182 +}
183 +
184 +static void *AFHTTPRequestSerializerObserverContext = &AFHTTPRequestSerializerObserverContext;
185 +
186 +@interface AFHTTPRequestSerializer ()
187 +@property (readwrite, nonatomic, strong) NSMutableSet *mutableObservedChangedKeyPaths;
188 +@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableHTTPRequestHeaders;
189 +@property (readwrite, nonatomic, strong) dispatch_queue_t requestHeaderModificationQueue;
190 +@property (readwrite, nonatomic, assign) AFHTTPRequestQueryStringSerializationStyle queryStringSerializationStyle;
191 +@property (readwrite, nonatomic, copy) AFQueryStringSerializationBlock queryStringSerialization;
192 +@end
193 +
194 +@implementation AFHTTPRequestSerializer
195 +
196 ++ (instancetype)serializer {
197 + return [[self alloc] init];
198 +}
199 +
200 +- (instancetype)init {
201 + self = [super init];
202 + if (!self) {
203 + return nil;
204 + }
205 +
206 + self.stringEncoding = NSUTF8StringEncoding;
207 +
208 + self.mutableHTTPRequestHeaders = [NSMutableDictionary dictionary];
209 + self.requestHeaderModificationQueue = dispatch_queue_create("requestHeaderModificationQueue", DISPATCH_QUEUE_CONCURRENT);
210 +
211 + // Accept-Language HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
212 + NSMutableArray *acceptLanguagesComponents = [NSMutableArray array];
213 + [[NSLocale preferredLanguages] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
214 + float q = 1.0f - (idx * 0.1f);
215 + [acceptLanguagesComponents addObject:[NSString stringWithFormat:@"%@;q=%0.1g", obj, q]];
216 + *stop = q <= 0.5f;
217 + }];
218 + [self setValue:[acceptLanguagesComponents componentsJoinedByString:@", "] forHTTPHeaderField:@"Accept-Language"];
219 +
220 + NSString *userAgent = nil;
221 +#if TARGET_OS_IOS
222 + // User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43
223 + 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]];
224 +#elif TARGET_OS_WATCH
225 + // User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43
226 + 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]];
227 +#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
228 + 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]];
229 +#endif
230 + if (userAgent) {
231 + if (![userAgent canBeConvertedToEncoding:NSASCIIStringEncoding]) {
232 + NSMutableString *mutableUserAgent = [userAgent mutableCopy];
233 + if (CFStringTransform((__bridge CFMutableStringRef)(mutableUserAgent), NULL, (__bridge CFStringRef)@"Any-Latin; Latin-ASCII; [:^ASCII:] Remove", false)) {
234 + userAgent = mutableUserAgent;
235 + }
236 + }
237 + [self setValue:userAgent forHTTPHeaderField:@"User-Agent"];
238 + }
239 +
240 + // HTTP Method Definitions; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
241 + self.HTTPMethodsEncodingParametersInURI = [NSSet setWithObjects:@"GET", @"HEAD", @"DELETE", nil];
242 +
243 + self.mutableObservedChangedKeyPaths = [NSMutableSet set];
244 + for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) {
245 + if ([self respondsToSelector:NSSelectorFromString(keyPath)]) {
246 + [self addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:AFHTTPRequestSerializerObserverContext];
247 + }
248 + }
249 +
250 + return self;
251 +}
252 +
253 +- (void)dealloc {
254 + for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) {
255 + if ([self respondsToSelector:NSSelectorFromString(keyPath)]) {
256 + [self removeObserver:self forKeyPath:keyPath context:AFHTTPRequestSerializerObserverContext];
257 + }
258 + }
259 +}
260 +
261 +#pragma mark -
262 +
263 +// Workarounds for crashing behavior using Key-Value Observing with XCTest
264 +// See https://github.com/AFNetworking/AFNetworking/issues/2523
265 +
266 +- (void)setAllowsCellularAccess:(BOOL)allowsCellularAccess {
267 + [self willChangeValueForKey:NSStringFromSelector(@selector(allowsCellularAccess))];
268 + _allowsCellularAccess = allowsCellularAccess;
269 + [self didChangeValueForKey:NSStringFromSelector(@selector(allowsCellularAccess))];
270 +}
271 +
272 +- (void)setCachePolicy:(NSURLRequestCachePolicy)cachePolicy {
273 + [self willChangeValueForKey:NSStringFromSelector(@selector(cachePolicy))];
274 + _cachePolicy = cachePolicy;
275 + [self didChangeValueForKey:NSStringFromSelector(@selector(cachePolicy))];
276 +}
277 +
278 +- (void)setHTTPShouldHandleCookies:(BOOL)HTTPShouldHandleCookies {
279 + [self willChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldHandleCookies))];
280 + _HTTPShouldHandleCookies = HTTPShouldHandleCookies;
281 + [self didChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldHandleCookies))];
282 +}
283 +
284 +- (void)setHTTPShouldUsePipelining:(BOOL)HTTPShouldUsePipelining {
285 + [self willChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldUsePipelining))];
286 + _HTTPShouldUsePipelining = HTTPShouldUsePipelining;
287 + [self didChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldUsePipelining))];
288 +}
289 +
290 +- (void)setNetworkServiceType:(NSURLRequestNetworkServiceType)networkServiceType {
291 + [self willChangeValueForKey:NSStringFromSelector(@selector(networkServiceType))];
292 + _networkServiceType = networkServiceType;
293 + [self didChangeValueForKey:NSStringFromSelector(@selector(networkServiceType))];
294 +}
295 +
296 +- (void)setTimeoutInterval:(NSTimeInterval)timeoutInterval {
297 + [self willChangeValueForKey:NSStringFromSelector(@selector(timeoutInterval))];
298 + _timeoutInterval = timeoutInterval;
299 + [self didChangeValueForKey:NSStringFromSelector(@selector(timeoutInterval))];
300 +}
301 +
302 +#pragma mark -
303 +
304 +- (NSDictionary *)HTTPRequestHeaders {
305 + NSDictionary __block *value;
306 + dispatch_sync(self.requestHeaderModificationQueue, ^{
307 + value = [NSDictionary dictionaryWithDictionary:self.mutableHTTPRequestHeaders];
308 + });
309 + return value;
310 +}
311 +
312 +- (void)setValue:(NSString *)value
313 +forHTTPHeaderField:(NSString *)field
314 +{
315 + dispatch_barrier_async(self.requestHeaderModificationQueue, ^{
316 + [self.mutableHTTPRequestHeaders setValue:value forKey:field];
317 + });
318 +}
319 +
320 +- (NSString *)valueForHTTPHeaderField:(NSString *)field {
321 + NSString __block *value;
322 + dispatch_sync(self.requestHeaderModificationQueue, ^{
323 + value = [self.mutableHTTPRequestHeaders valueForKey:field];
324 + });
325 + return value;
326 +}
327 +
328 +- (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username
329 + password:(NSString *)password
330 +{
331 + NSData *basicAuthCredentials = [[NSString stringWithFormat:@"%@:%@", username, password] dataUsingEncoding:NSUTF8StringEncoding];
332 + NSString *base64AuthCredentials = [basicAuthCredentials base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)0];
333 + [self setValue:[NSString stringWithFormat:@"Basic %@", base64AuthCredentials] forHTTPHeaderField:@"Authorization"];
334 +}
335 +
336 +- (void)clearAuthorizationHeader {
337 + dispatch_barrier_async(self.requestHeaderModificationQueue, ^{
338 + [self.mutableHTTPRequestHeaders removeObjectForKey:@"Authorization"];
339 + });
340 +}
341 +
342 +#pragma mark -
343 +
344 +- (void)setQueryStringSerializationWithStyle:(AFHTTPRequestQueryStringSerializationStyle)style {
345 + self.queryStringSerializationStyle = style;
346 + self.queryStringSerialization = nil;
347 +}
348 +
349 +- (void)setQueryStringSerializationWithBlock:(NSString *(^)(NSURLRequest *, id, NSError *__autoreleasing *))block {
350 + self.queryStringSerialization = block;
351 +}
352 +
353 +#pragma mark -
354 +
355 +- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
356 + URLString:(NSString *)URLString
357 + parameters:(id)parameters
358 + error:(NSError *__autoreleasing *)error
359 +{
360 + NSParameterAssert(method);
361 + NSParameterAssert(URLString);
362 +
363 + NSURL *url = [NSURL URLWithString:URLString];
364 +
365 + NSParameterAssert(url);
366 +
367 + NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL:url];
368 + mutableRequest.HTTPMethod = method;
369 +
370 + for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) {
371 + if ([self.mutableObservedChangedKeyPaths containsObject:keyPath]) {
372 + [mutableRequest setValue:[self valueForKeyPath:keyPath] forKey:keyPath];
373 + }
374 + }
375 +
376 + mutableRequest = [[self requestBySerializingRequest:mutableRequest withParameters:parameters error:error] mutableCopy];
377 +
378 + return mutableRequest;
379 +}
380 +
381 +- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
382 + URLString:(NSString *)URLString
383 + parameters:(NSDictionary *)parameters
384 + constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
385 + error:(NSError *__autoreleasing *)error
386 +{
387 + NSParameterAssert(method);
388 + NSParameterAssert(![method isEqualToString:@"GET"] && ![method isEqualToString:@"HEAD"]);
389 +
390 + NSMutableURLRequest *mutableRequest = [self requestWithMethod:method URLString:URLString parameters:nil error:error];
391 +
392 + __block AFStreamingMultipartFormData *formData = [[AFStreamingMultipartFormData alloc] initWithURLRequest:mutableRequest stringEncoding:NSUTF8StringEncoding];
393 +
394 + if (parameters) {
395 + for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) {
396 + NSData *data = nil;
397 + if ([pair.value isKindOfClass:[NSData class]]) {
398 + data = pair.value;
399 + } else if ([pair.value isEqual:[NSNull null]]) {
400 + data = [NSData data];
401 + } else {
402 + data = [[pair.value description] dataUsingEncoding:self.stringEncoding];
403 + }
404 +
405 + if (data) {
406 + [formData appendPartWithFormData:data name:[pair.field description]];
407 + }
408 + }
409 + }
410 +
411 + if (block) {
412 + block(formData);
413 + }
414 +
415 + return [formData requestByFinalizingMultipartFormData];
416 +}
417 +
418 +- (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request
419 + writingStreamContentsToFile:(NSURL *)fileURL
420 + completionHandler:(void (^)(NSError *error))handler
421 +{
422 + NSParameterAssert(request.HTTPBodyStream);
423 + NSParameterAssert([fileURL isFileURL]);
424 +
425 + NSInputStream *inputStream = request.HTTPBodyStream;
426 + NSOutputStream *outputStream = [[NSOutputStream alloc] initWithURL:fileURL append:NO];
427 + __block NSError *error = nil;
428 +
429 + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
430 + [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
431 + [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
432 +
433 + [inputStream open];
434 + [outputStream open];
435 +
436 + while ([inputStream hasBytesAvailable] && [outputStream hasSpaceAvailable]) {
437 + uint8_t buffer[1024];
438 +
439 + NSInteger bytesRead = [inputStream read:buffer maxLength:1024];
440 + if (inputStream.streamError || bytesRead < 0) {
441 + error = inputStream.streamError;
442 + break;
443 + }
444 +
445 + NSInteger bytesWritten = [outputStream write:buffer maxLength:(NSUInteger)bytesRead];
446 + if (outputStream.streamError || bytesWritten < 0) {
447 + error = outputStream.streamError;
448 + break;
449 + }
450 +
451 + if (bytesRead == 0 && bytesWritten == 0) {
452 + break;
453 + }
454 + }
455 +
456 + [outputStream close];
457 + [inputStream close];
458 +
459 + if (handler) {
460 + dispatch_async(dispatch_get_main_queue(), ^{
461 + handler(error);
462 + });
463 + }
464 + });
465 +
466 + NSMutableURLRequest *mutableRequest = [request mutableCopy];
467 + mutableRequest.HTTPBodyStream = nil;
468 +
469 + return mutableRequest;
470 +}
471 +
472 +#pragma mark - AFURLRequestSerialization
473 +
474 +- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
475 + withParameters:(id)parameters
476 + error:(NSError *__autoreleasing *)error
477 +{
478 + NSParameterAssert(request);
479 +
480 + NSMutableURLRequest *mutableRequest = [request mutableCopy];
481 +
482 + [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
483 + if (![request valueForHTTPHeaderField:field]) {
484 + [mutableRequest setValue:value forHTTPHeaderField:field];
485 + }
486 + }];
487 +
488 + NSString *query = nil;
489 + if (parameters) {
490 + if (self.queryStringSerialization) {
491 + NSError *serializationError;
492 + query = self.queryStringSerialization(request, parameters, &serializationError);
493 +
494 + if (serializationError) {
495 + if (error) {
496 + *error = serializationError;
497 + }
498 +
499 + return nil;
500 + }
501 + } else {
502 + switch (self.queryStringSerializationStyle) {
503 + case AFHTTPRequestQueryStringDefaultStyle:
504 + query = AFQueryStringFromParameters(parameters);
505 + break;
506 + }
507 + }
508 + }
509 +
510 + if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
511 + if (query && query.length > 0) {
512 + mutableRequest.URL = [NSURL URLWithString:[[mutableRequest.URL absoluteString] stringByAppendingFormat:mutableRequest.URL.query ? @"&%@" : @"?%@", query]];
513 + }
514 + } else {
515 + // #2864: an empty string is a valid x-www-form-urlencoded payload
516 + if (!query) {
517 + query = @"";
518 + }
519 + if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) {
520 + [mutableRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
521 + }
522 + [mutableRequest setHTTPBody:[query dataUsingEncoding:self.stringEncoding]];
523 + }
524 +
525 + return mutableRequest;
526 +}
527 +
528 +#pragma mark - NSKeyValueObserving
529 +
530 ++ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
531 + if ([AFHTTPRequestSerializerObservedKeyPaths() containsObject:key]) {
532 + return NO;
533 + }
534 +
535 + return [super automaticallyNotifiesObserversForKey:key];
536 +}
537 +
538 +- (void)observeValueForKeyPath:(NSString *)keyPath
539 + ofObject:(__unused id)object
540 + change:(NSDictionary *)change
541 + context:(void *)context
542 +{
543 + if (context == AFHTTPRequestSerializerObserverContext) {
544 + if ([change[NSKeyValueChangeNewKey] isEqual:[NSNull null]]) {
545 + [self.mutableObservedChangedKeyPaths removeObject:keyPath];
546 + } else {
547 + [self.mutableObservedChangedKeyPaths addObject:keyPath];
548 + }
549 + }
550 +}
551 +
552 +#pragma mark - NSSecureCoding
553 +
554 ++ (BOOL)supportsSecureCoding {
555 + return YES;
556 +}
557 +
558 +- (instancetype)initWithCoder:(NSCoder *)decoder {
559 + self = [self init];
560 + if (!self) {
561 + return nil;
562 + }
563 +
564 + self.mutableHTTPRequestHeaders = [[decoder decodeObjectOfClass:[NSDictionary class] forKey:NSStringFromSelector(@selector(mutableHTTPRequestHeaders))] mutableCopy];
565 + self.queryStringSerializationStyle = (AFHTTPRequestQueryStringSerializationStyle)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))] unsignedIntegerValue];
566 +
567 + return self;
568 +}
569 +
570 +- (void)encodeWithCoder:(NSCoder *)coder {
571 + dispatch_sync(self.requestHeaderModificationQueue, ^{
572 + [coder encodeObject:self.mutableHTTPRequestHeaders forKey:NSStringFromSelector(@selector(mutableHTTPRequestHeaders))];
573 + });
574 + [coder encodeInteger:self.queryStringSerializationStyle forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))];
575 +}
576 +
577 +#pragma mark - NSCopying
578 +
579 +- (instancetype)copyWithZone:(NSZone *)zone {
580 + AFHTTPRequestSerializer *serializer = [[[self class] allocWithZone:zone] init];
581 + dispatch_sync(self.requestHeaderModificationQueue, ^{
582 + serializer.mutableHTTPRequestHeaders = [self.mutableHTTPRequestHeaders mutableCopyWithZone:zone];
583 + });
584 + serializer.queryStringSerializationStyle = self.queryStringSerializationStyle;
585 + serializer.queryStringSerialization = self.queryStringSerialization;
586 +
587 + return serializer;
588 +}
589 +
590 +@end
591 +
592 +#pragma mark -
593 +
594 +static NSString * AFCreateMultipartFormBoundary() {
595 + return [NSString stringWithFormat:@"Boundary+%08X%08X", arc4random(), arc4random()];
596 +}
597 +
598 +static NSString * const kAFMultipartFormCRLF = @"\r\n";
599 +
600 +static inline NSString * AFMultipartFormInitialBoundary(NSString *boundary) {
601 + return [NSString stringWithFormat:@"--%@%@", boundary, kAFMultipartFormCRLF];
602 +}
603 +
604 +static inline NSString * AFMultipartFormEncapsulationBoundary(NSString *boundary) {
605 + return [NSString stringWithFormat:@"%@--%@%@", kAFMultipartFormCRLF, boundary, kAFMultipartFormCRLF];
606 +}
607 +
608 +static inline NSString * AFMultipartFormFinalBoundary(NSString *boundary) {
609 + return [NSString stringWithFormat:@"%@--%@--%@", kAFMultipartFormCRLF, boundary, kAFMultipartFormCRLF];
610 +}
611 +
612 +static inline NSString * AFContentTypeForPathExtension(NSString *extension) {
613 + NSString *UTI = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)extension, NULL);
614 + NSString *contentType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)UTI, kUTTagClassMIMEType);
615 + if (!contentType) {
616 + return @"application/octet-stream";
617 + } else {
618 + return contentType;
619 + }
620 +}
621 +
622 +NSUInteger const kAFUploadStream3GSuggestedPacketSize = 1024 * 16;
623 +NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
624 +
625 +@interface AFHTTPBodyPart : NSObject
626 +@property (nonatomic, assign) NSStringEncoding stringEncoding;
627 +@property (nonatomic, strong) NSDictionary *headers;
628 +@property (nonatomic, copy) NSString *boundary;
629 +@property (nonatomic, strong) id body;
630 +@property (nonatomic, assign) unsigned long long bodyContentLength;
631 +@property (nonatomic, strong) NSInputStream *inputStream;
632 +
633 +@property (nonatomic, assign) BOOL hasInitialBoundary;
634 +@property (nonatomic, assign) BOOL hasFinalBoundary;
635 +
636 +@property (readonly, nonatomic, assign, getter = hasBytesAvailable) BOOL bytesAvailable;
637 +@property (readonly, nonatomic, assign) unsigned long long contentLength;
638 +
639 +- (NSInteger)read:(uint8_t *)buffer
640 + maxLength:(NSUInteger)length;
641 +@end
642 +
643 +@interface AFMultipartBodyStream : NSInputStream <NSStreamDelegate>
644 +@property (nonatomic, assign) NSUInteger numberOfBytesInPacket;
645 +@property (nonatomic, assign) NSTimeInterval delay;
646 +@property (nonatomic, strong) NSInputStream *inputStream;
647 +@property (readonly, nonatomic, assign) unsigned long long contentLength;
648 +@property (readonly, nonatomic, assign, getter = isEmpty) BOOL empty;
649 +
650 +- (instancetype)initWithStringEncoding:(NSStringEncoding)encoding;
651 +- (void)setInitialAndFinalBoundaries;
652 +- (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart;
653 +@end
654 +
655 +#pragma mark -
656 +
657 +@interface AFStreamingMultipartFormData ()
658 +@property (readwrite, nonatomic, copy) NSMutableURLRequest *request;
659 +@property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding;
660 +@property (readwrite, nonatomic, copy) NSString *boundary;
661 +@property (readwrite, nonatomic, strong) AFMultipartBodyStream *bodyStream;
662 +@end
663 +
664 +@implementation AFStreamingMultipartFormData
665 +
666 +- (instancetype)initWithURLRequest:(NSMutableURLRequest *)urlRequest
667 + stringEncoding:(NSStringEncoding)encoding
668 +{
669 + self = [super init];
670 + if (!self) {
671 + return nil;
672 + }
673 +
674 + self.request = urlRequest;
675 + self.stringEncoding = encoding;
676 + self.boundary = AFCreateMultipartFormBoundary();
677 + self.bodyStream = [[AFMultipartBodyStream alloc] initWithStringEncoding:encoding];
678 +
679 + return self;
680 +}
681 +
682 +- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
683 + name:(NSString *)name
684 + error:(NSError * __autoreleasing *)error
685 +{
686 + NSParameterAssert(fileURL);
687 + NSParameterAssert(name);
688 +
689 + NSString *fileName = [fileURL lastPathComponent];
690 + NSString *mimeType = AFContentTypeForPathExtension([fileURL pathExtension]);
691 +
692 + return [self appendPartWithFileURL:fileURL name:name fileName:fileName mimeType:mimeType error:error];
693 +}
694 +
695 +- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
696 + name:(NSString *)name
697 + fileName:(NSString *)fileName
698 + mimeType:(NSString *)mimeType
699 + error:(NSError * __autoreleasing *)error
700 +{
701 + NSParameterAssert(fileURL);
702 + NSParameterAssert(name);
703 + NSParameterAssert(fileName);
704 + NSParameterAssert(mimeType);
705 +
706 + if (![fileURL isFileURL]) {
707 + NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"Expected URL to be a file URL", @"AFNetworking", nil)};
708 + if (error) {
709 + *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorBadURL userInfo:userInfo];
710 + }
711 +
712 + return NO;
713 + } else if ([fileURL checkResourceIsReachableAndReturnError:error] == NO) {
714 + NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"File URL not reachable.", @"AFNetworking", nil)};
715 + if (error) {
716 + *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorBadURL userInfo:userInfo];
717 + }
718 +
719 + return NO;
720 + }
721 +
722 + NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[fileURL path] error:error];
723 + if (!fileAttributes) {
724 + return NO;
725 + }
726 +
727 + NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
728 + [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"];
729 + [mutableHeaders setValue:mimeType forKey:@"Content-Type"];
730 +
731 + AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init];
732 + bodyPart.stringEncoding = self.stringEncoding;
733 + bodyPart.headers = mutableHeaders;
734 + bodyPart.boundary = self.boundary;
735 + bodyPart.body = fileURL;
736 + bodyPart.bodyContentLength = [fileAttributes[NSFileSize] unsignedLongLongValue];
737 + [self.bodyStream appendHTTPBodyPart:bodyPart];
738 +
739 + return YES;
740 +}
741 +
742 +- (void)appendPartWithInputStream:(NSInputStream *)inputStream
743 + name:(NSString *)name
744 + fileName:(NSString *)fileName
745 + length:(int64_t)length
746 + mimeType:(NSString *)mimeType
747 +{
748 + NSParameterAssert(name);
749 + NSParameterAssert(fileName);
750 + NSParameterAssert(mimeType);
751 +
752 + NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
753 + [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"];
754 + [mutableHeaders setValue:mimeType forKey:@"Content-Type"];
755 +
756 + AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init];
757 + bodyPart.stringEncoding = self.stringEncoding;
758 + bodyPart.headers = mutableHeaders;
759 + bodyPart.boundary = self.boundary;
760 + bodyPart.body = inputStream;
761 +
762 + bodyPart.bodyContentLength = (unsigned long long)length;
763 +
764 + [self.bodyStream appendHTTPBodyPart:bodyPart];
765 +}
766 +
767 +- (void)appendPartWithFileData:(NSData *)data
768 + name:(NSString *)name
769 + fileName:(NSString *)fileName
770 + mimeType:(NSString *)mimeType
771 +{
772 + NSParameterAssert(name);
773 + NSParameterAssert(fileName);
774 + NSParameterAssert(mimeType);
775 +
776 + NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
777 + [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"];
778 + [mutableHeaders setValue:mimeType forKey:@"Content-Type"];
779 +
780 + [self appendPartWithHeaders:mutableHeaders body:data];
781 +}
782 +
783 +- (void)appendPartWithFormData:(NSData *)data
784 + name:(NSString *)name
785 +{
786 + NSParameterAssert(name);
787 +
788 + NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
789 + [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"", name] forKey:@"Content-Disposition"];
790 +
791 + [self appendPartWithHeaders:mutableHeaders body:data];
792 +}
793 +
794 +- (void)appendPartWithHeaders:(NSDictionary *)headers
795 + body:(NSData *)body
796 +{
797 + NSParameterAssert(body);
798 +
799 + AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init];
800 + bodyPart.stringEncoding = self.stringEncoding;
801 + bodyPart.headers = headers;
802 + bodyPart.boundary = self.boundary;
803 + bodyPart.bodyContentLength = [body length];
804 + bodyPart.body = body;
805 +
806 + [self.bodyStream appendHTTPBodyPart:bodyPart];
807 +}
808 +
809 +- (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes
810 + delay:(NSTimeInterval)delay
811 +{
812 + self.bodyStream.numberOfBytesInPacket = numberOfBytes;
813 + self.bodyStream.delay = delay;
814 +}
815 +
816 +- (NSMutableURLRequest *)requestByFinalizingMultipartFormData {
817 + if ([self.bodyStream isEmpty]) {
818 + return self.request;
819 + }
820 +
821 + // Reset the initial and final boundaries to ensure correct Content-Length
822 + [self.bodyStream setInitialAndFinalBoundaries];
823 + [self.request setHTTPBodyStream:self.bodyStream];
824 +
825 + [self.request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", self.boundary] forHTTPHeaderField:@"Content-Type"];
826 + [self.request setValue:[NSString stringWithFormat:@"%llu", [self.bodyStream contentLength]] forHTTPHeaderField:@"Content-Length"];
827 +
828 + return self.request;
829 +}
830 +
831 +@end
832 +
833 +#pragma mark -
834 +
835 +@interface NSStream ()
836 +@property (readwrite) NSStreamStatus streamStatus;
837 +@property (readwrite, copy) NSError *streamError;
838 +@end
839 +
840 +@interface AFMultipartBodyStream () <NSCopying>
841 +@property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding;
842 +@property (readwrite, nonatomic, strong) NSMutableArray *HTTPBodyParts;
843 +@property (readwrite, nonatomic, strong) NSEnumerator *HTTPBodyPartEnumerator;
844 +@property (readwrite, nonatomic, strong) AFHTTPBodyPart *currentHTTPBodyPart;
845 +@property (readwrite, nonatomic, strong) NSOutputStream *outputStream;
846 +@property (readwrite, nonatomic, strong) NSMutableData *buffer;
847 +@end
848 +
849 +@implementation AFMultipartBodyStream
850 +#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)
851 +@synthesize delegate;
852 +#endif
853 +@synthesize streamStatus;
854 +@synthesize streamError;
855 +
856 +- (instancetype)initWithStringEncoding:(NSStringEncoding)encoding {
857 + self = [super init];
858 + if (!self) {
859 + return nil;
860 + }
861 +
862 + self.stringEncoding = encoding;
863 + self.HTTPBodyParts = [NSMutableArray array];
864 + self.numberOfBytesInPacket = NSIntegerMax;
865 +
866 + return self;
867 +}
868 +
869 +- (void)setInitialAndFinalBoundaries {
870 + if ([self.HTTPBodyParts count] > 0) {
871 + for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) {
872 + bodyPart.hasInitialBoundary = NO;
873 + bodyPart.hasFinalBoundary = NO;
874 + }
875 +
876 + [[self.HTTPBodyParts firstObject] setHasInitialBoundary:YES];
877 + [[self.HTTPBodyParts lastObject] setHasFinalBoundary:YES];
878 + }
879 +}
880 +
881 +- (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart {
882 + [self.HTTPBodyParts addObject:bodyPart];
883 +}
884 +
885 +- (BOOL)isEmpty {
886 + return [self.HTTPBodyParts count] == 0;
887 +}
888 +
889 +#pragma mark - NSInputStream
890 +
891 +- (NSInteger)read:(uint8_t *)buffer
892 + maxLength:(NSUInteger)length
893 +{
894 + if ([self streamStatus] == NSStreamStatusClosed) {
895 + return 0;
896 + }
897 +
898 + NSInteger totalNumberOfBytesRead = 0;
899 +
900 + while ((NSUInteger)totalNumberOfBytesRead < MIN(length, self.numberOfBytesInPacket)) {
901 + if (!self.currentHTTPBodyPart || ![self.currentHTTPBodyPart hasBytesAvailable]) {
902 + if (!(self.currentHTTPBodyPart = [self.HTTPBodyPartEnumerator nextObject])) {
903 + break;
904 + }
905 + } else {
906 + NSUInteger maxLength = MIN(length, self.numberOfBytesInPacket) - (NSUInteger)totalNumberOfBytesRead;
907 + NSInteger numberOfBytesRead = [self.currentHTTPBodyPart read:&buffer[totalNumberOfBytesRead] maxLength:maxLength];
908 + if (numberOfBytesRead == -1) {
909 + self.streamError = self.currentHTTPBodyPart.inputStream.streamError;
910 + break;
911 + } else {
912 + totalNumberOfBytesRead += numberOfBytesRead;
913 +
914 + if (self.delay > 0.0f) {
915 + [NSThread sleepForTimeInterval:self.delay];
916 + }
917 + }
918 + }
919 + }
920 +
921 + return totalNumberOfBytesRead;
922 +}
923 +
924 +- (BOOL)getBuffer:(__unused uint8_t **)buffer
925 + length:(__unused NSUInteger *)len
926 +{
927 + return NO;
928 +}
929 +
930 +- (BOOL)hasBytesAvailable {
931 + return [self streamStatus] == NSStreamStatusOpen;
932 +}
933 +
934 +#pragma mark - NSStream
935 +
936 +- (void)open {
937 + if (self.streamStatus == NSStreamStatusOpen) {
938 + return;
939 + }
940 +
941 + self.streamStatus = NSStreamStatusOpen;
942 +
943 + [self setInitialAndFinalBoundaries];
944 + self.HTTPBodyPartEnumerator = [self.HTTPBodyParts objectEnumerator];
945 +}
946 +
947 +- (void)close {
948 + self.streamStatus = NSStreamStatusClosed;
949 +}
950 +
951 +- (id)propertyForKey:(__unused NSString *)key {
952 + return nil;
953 +}
954 +
955 +- (BOOL)setProperty:(__unused id)property
956 + forKey:(__unused NSString *)key
957 +{
958 + return NO;
959 +}
960 +
961 +- (void)scheduleInRunLoop:(__unused NSRunLoop *)aRunLoop
962 + forMode:(__unused NSString *)mode
963 +{}
964 +
965 +- (void)removeFromRunLoop:(__unused NSRunLoop *)aRunLoop
966 + forMode:(__unused NSString *)mode
967 +{}
968 +
969 +- (unsigned long long)contentLength {
970 + unsigned long long length = 0;
971 + for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) {
972 + length += [bodyPart contentLength];
973 + }
974 +
975 + return length;
976 +}
977 +
978 +#pragma mark - Undocumented CFReadStream Bridged Methods
979 +
980 +- (void)_scheduleInCFRunLoop:(__unused CFRunLoopRef)aRunLoop
981 + forMode:(__unused CFStringRef)aMode
982 +{}
983 +
984 +- (void)_unscheduleFromCFRunLoop:(__unused CFRunLoopRef)aRunLoop
985 + forMode:(__unused CFStringRef)aMode
986 +{}
987 +
988 +- (BOOL)_setCFClientFlags:(__unused CFOptionFlags)inFlags
989 + callback:(__unused CFReadStreamClientCallBack)inCallback
990 + context:(__unused CFStreamClientContext *)inContext {
991 + return NO;
992 +}
993 +
994 +#pragma mark - NSCopying
995 +
996 +- (instancetype)copyWithZone:(NSZone *)zone {
997 + AFMultipartBodyStream *bodyStreamCopy = [[[self class] allocWithZone:zone] initWithStringEncoding:self.stringEncoding];
998 +
999 + for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) {
1000 + [bodyStreamCopy appendHTTPBodyPart:[bodyPart copy]];
1001 + }
1002 +
1003 + [bodyStreamCopy setInitialAndFinalBoundaries];
1004 +
1005 + return bodyStreamCopy;
1006 +}
1007 +
1008 +@end
1009 +
1010 +#pragma mark -
1011 +
1012 +typedef enum {
1013 + AFEncapsulationBoundaryPhase = 1,
1014 + AFHeaderPhase = 2,
1015 + AFBodyPhase = 3,
1016 + AFFinalBoundaryPhase = 4,
1017 +} AFHTTPBodyPartReadPhase;
1018 +
1019 +@interface AFHTTPBodyPart () <NSCopying> {
1020 + AFHTTPBodyPartReadPhase _phase;
1021 + NSInputStream *_inputStream;
1022 + unsigned long long _phaseReadOffset;
1023 +}
1024 +
1025 +- (BOOL)transitionToNextPhase;
1026 +- (NSInteger)readData:(NSData *)data
1027 + intoBuffer:(uint8_t *)buffer
1028 + maxLength:(NSUInteger)length;
1029 +@end
1030 +
1031 +@implementation AFHTTPBodyPart
1032 +
1033 +- (instancetype)init {
1034 + self = [super init];
1035 + if (!self) {
1036 + return nil;
1037 + }
1038 +
1039 + [self transitionToNextPhase];
1040 +
1041 + return self;
1042 +}
1043 +
1044 +- (void)dealloc {
1045 + if (_inputStream) {
1046 + [_inputStream close];
1047 + _inputStream = nil;
1048 + }
1049 +}
1050 +
1051 +- (NSInputStream *)inputStream {
1052 + if (!_inputStream) {
1053 + if ([self.body isKindOfClass:[NSData class]]) {
1054 + _inputStream = [NSInputStream inputStreamWithData:self.body];
1055 + } else if ([self.body isKindOfClass:[NSURL class]]) {
1056 + _inputStream = [NSInputStream inputStreamWithURL:self.body];
1057 + } else if ([self.body isKindOfClass:[NSInputStream class]]) {
1058 + _inputStream = self.body;
1059 + } else {
1060 + _inputStream = [NSInputStream inputStreamWithData:[NSData data]];
1061 + }
1062 + }
1063 +
1064 + return _inputStream;
1065 +}
1066 +
1067 +- (NSString *)stringForHeaders {
1068 + NSMutableString *headerString = [NSMutableString string];
1069 + for (NSString *field in [self.headers allKeys]) {
1070 + [headerString appendString:[NSString stringWithFormat:@"%@: %@%@", field, [self.headers valueForKey:field], kAFMultipartFormCRLF]];
1071 + }
1072 + [headerString appendString:kAFMultipartFormCRLF];
1073 +
1074 + return [NSString stringWithString:headerString];
1075 +}
1076 +
1077 +- (unsigned long long)contentLength {
1078 + unsigned long long length = 0;
1079 +
1080 + NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary(self.boundary) : AFMultipartFormEncapsulationBoundary(self.boundary)) dataUsingEncoding:self.stringEncoding];
1081 + length += [encapsulationBoundaryData length];
1082 +
1083 + NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding];
1084 + length += [headersData length];
1085 +
1086 + length += _bodyContentLength;
1087 +
1088 + NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary(self.boundary) dataUsingEncoding:self.stringEncoding] : [NSData data]);
1089 + length += [closingBoundaryData length];
1090 +
1091 + return length;
1092 +}
1093 +
1094 +- (BOOL)hasBytesAvailable {
1095 + // Allows `read:maxLength:` to be called again if `AFMultipartFormFinalBoundary` doesn't fit into the available buffer
1096 + if (_phase == AFFinalBoundaryPhase) {
1097 + return YES;
1098 + }
1099 +
1100 + switch (self.inputStream.streamStatus) {
1101 + case NSStreamStatusNotOpen:
1102 + case NSStreamStatusOpening:
1103 + case NSStreamStatusOpen:
1104 + case NSStreamStatusReading:
1105 + case NSStreamStatusWriting:
1106 + return YES;
1107 + case NSStreamStatusAtEnd:
1108 + case NSStreamStatusClosed:
1109 + case NSStreamStatusError:
1110 + default:
1111 + return NO;
1112 + }
1113 +}
1114 +
1115 +- (NSInteger)read:(uint8_t *)buffer
1116 + maxLength:(NSUInteger)length
1117 +{
1118 + NSInteger totalNumberOfBytesRead = 0;
1119 +
1120 + if (_phase == AFEncapsulationBoundaryPhase) {
1121 + NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary(self.boundary) : AFMultipartFormEncapsulationBoundary(self.boundary)) dataUsingEncoding:self.stringEncoding];
1122 + totalNumberOfBytesRead += [self readData:encapsulationBoundaryData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)];
1123 + }
1124 +
1125 + if (_phase == AFHeaderPhase) {
1126 + NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding];
1127 + totalNumberOfBytesRead += [self readData:headersData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)];
1128 + }
1129 +
1130 + if (_phase == AFBodyPhase) {
1131 + NSInteger numberOfBytesRead = 0;
1132 +
1133 + numberOfBytesRead = [self.inputStream read:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)];
1134 + if (numberOfBytesRead == -1) {
1135 + return -1;
1136 + } else {
1137 + totalNumberOfBytesRead += numberOfBytesRead;
1138 +
1139 + if ([self.inputStream streamStatus] >= NSStreamStatusAtEnd) {
1140 + [self transitionToNextPhase];
1141 + }
1142 + }
1143 + }
1144 +
1145 + if (_phase == AFFinalBoundaryPhase) {
1146 + NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary(self.boundary) dataUsingEncoding:self.stringEncoding] : [NSData data]);
1147 + totalNumberOfBytesRead += [self readData:closingBoundaryData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)];
1148 + }
1149 +
1150 + return totalNumberOfBytesRead;
1151 +}
1152 +
1153 +- (NSInteger)readData:(NSData *)data
1154 + intoBuffer:(uint8_t *)buffer
1155 + maxLength:(NSUInteger)length
1156 +{
1157 + NSRange range = NSMakeRange((NSUInteger)_phaseReadOffset, MIN([data length] - ((NSUInteger)_phaseReadOffset), length));
1158 + [data getBytes:buffer range:range];
1159 +
1160 + _phaseReadOffset += range.length;
1161 +
1162 + if (((NSUInteger)_phaseReadOffset) >= [data length]) {
1163 + [self transitionToNextPhase];
1164 + }
1165 +
1166 + return (NSInteger)range.length;
1167 +}
1168 +
1169 +- (BOOL)transitionToNextPhase {
1170 + if (![[NSThread currentThread] isMainThread]) {
1171 + dispatch_sync(dispatch_get_main_queue(), ^{
1172 + [self transitionToNextPhase];
1173 + });
1174 + return YES;
1175 + }
1176 +
1177 + switch (_phase) {
1178 + case AFEncapsulationBoundaryPhase:
1179 + _phase = AFHeaderPhase;
1180 + break;
1181 + case AFHeaderPhase:
1182 + [self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
1183 + [self.inputStream open];
1184 + _phase = AFBodyPhase;
1185 + break;
1186 + case AFBodyPhase:
1187 + [self.inputStream close];
1188 + _phase = AFFinalBoundaryPhase;
1189 + break;
1190 + case AFFinalBoundaryPhase:
1191 + default:
1192 + _phase = AFEncapsulationBoundaryPhase;
1193 + break;
1194 + }
1195 + _phaseReadOffset = 0;
1196 +
1197 + return YES;
1198 +}
1199 +
1200 +#pragma mark - NSCopying
1201 +
1202 +- (instancetype)copyWithZone:(NSZone *)zone {
1203 + AFHTTPBodyPart *bodyPart = [[[self class] allocWithZone:zone] init];
1204 +
1205 + bodyPart.stringEncoding = self.stringEncoding;
1206 + bodyPart.headers = self.headers;
1207 + bodyPart.bodyContentLength = self.bodyContentLength;
1208 + bodyPart.body = self.body;
1209 + bodyPart.boundary = self.boundary;
1210 +
1211 + return bodyPart;
1212 +}
1213 +
1214 +@end
1215 +
1216 +#pragma mark -
1217 +
1218 +@implementation AFJSONRequestSerializer
1219 +
1220 ++ (instancetype)serializer {
1221 + return [self serializerWithWritingOptions:(NSJSONWritingOptions)0];
1222 +}
1223 +
1224 ++ (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions
1225 +{
1226 + AFJSONRequestSerializer *serializer = [[self alloc] init];
1227 + serializer.writingOptions = writingOptions;
1228 +
1229 + return serializer;
1230 +}
1231 +
1232 +#pragma mark - AFURLRequestSerialization
1233 +
1234 +- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
1235 + withParameters:(id)parameters
1236 + error:(NSError *__autoreleasing *)error
1237 +{
1238 + NSParameterAssert(request);
1239 +
1240 + if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
1241 + return [super requestBySerializingRequest:request withParameters:parameters error:error];
1242 + }
1243 +
1244 + NSMutableURLRequest *mutableRequest = [request mutableCopy];
1245 +
1246 + [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
1247 + if (![request valueForHTTPHeaderField:field]) {
1248 + [mutableRequest setValue:value forHTTPHeaderField:field];
1249 + }
1250 + }];
1251 +
1252 + if (parameters) {
1253 + if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) {
1254 + [mutableRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
1255 + }
1256 +
1257 + if (![NSJSONSerialization isValidJSONObject:parameters]) {
1258 + if (error) {
1259 + NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"The `parameters` argument is not valid JSON.", @"AFNetworking", nil)};
1260 + *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo];
1261 + }
1262 + return nil;
1263 + }
1264 +
1265 + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error];
1266 +
1267 + if (!jsonData) {
1268 + return nil;
1269 + }
1270 +
1271 + [mutableRequest setHTTPBody:jsonData];
1272 + }
1273 +
1274 + return mutableRequest;
1275 +}
1276 +
1277 +#pragma mark - NSSecureCoding
1278 +
1279 +- (instancetype)initWithCoder:(NSCoder *)decoder {
1280 + self = [super initWithCoder:decoder];
1281 + if (!self) {
1282 + return nil;
1283 + }
1284 +
1285 + self.writingOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(writingOptions))] unsignedIntegerValue];
1286 +
1287 + return self;
1288 +}
1289 +
1290 +- (void)encodeWithCoder:(NSCoder *)coder {
1291 + [super encodeWithCoder:coder];
1292 +
1293 + [coder encodeInteger:self.writingOptions forKey:NSStringFromSelector(@selector(writingOptions))];
1294 +}
1295 +
1296 +#pragma mark - NSCopying
1297 +
1298 +- (instancetype)copyWithZone:(NSZone *)zone {
1299 + AFJSONRequestSerializer *serializer = [super copyWithZone:zone];
1300 + serializer.writingOptions = self.writingOptions;
1301 +
1302 + return serializer;
1303 +}
1304 +
1305 +@end
1306 +
1307 +#pragma mark -
1308 +
1309 +@implementation AFPropertyListRequestSerializer
1310 +
1311 ++ (instancetype)serializer {
1312 + return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 writeOptions:0];
1313 +}
1314 +
1315 ++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format
1316 + writeOptions:(NSPropertyListWriteOptions)writeOptions
1317 +{
1318 + AFPropertyListRequestSerializer *serializer = [[self alloc] init];
1319 + serializer.format = format;
1320 + serializer.writeOptions = writeOptions;
1321 +
1322 + return serializer;
1323 +}
1324 +
1325 +#pragma mark - AFURLRequestSerializer
1326 +
1327 +- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
1328 + withParameters:(id)parameters
1329 + error:(NSError *__autoreleasing *)error
1330 +{
1331 + NSParameterAssert(request);
1332 +
1333 + if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
1334 + return [super requestBySerializingRequest:request withParameters:parameters error:error];
1335 + }
1336 +
1337 + NSMutableURLRequest *mutableRequest = [request mutableCopy];
1338 +
1339 + [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
1340 + if (![request valueForHTTPHeaderField:field]) {
1341 + [mutableRequest setValue:value forHTTPHeaderField:field];
1342 + }
1343 + }];
1344 +
1345 + if (parameters) {
1346 + if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) {
1347 + [mutableRequest setValue:@"application/x-plist" forHTTPHeaderField:@"Content-Type"];
1348 + }
1349 +
1350 + NSData *plistData = [NSPropertyListSerialization dataWithPropertyList:parameters format:self.format options:self.writeOptions error:error];
1351 +
1352 + if (!plistData) {
1353 + return nil;
1354 + }
1355 +
1356 + [mutableRequest setHTTPBody:plistData];
1357 + }
1358 +
1359 + return mutableRequest;
1360 +}
1361 +
1362 +#pragma mark - NSSecureCoding
1363 +
1364 +- (instancetype)initWithCoder:(NSCoder *)decoder {
1365 + self = [super initWithCoder:decoder];
1366 + if (!self) {
1367 + return nil;
1368 + }
1369 +
1370 + self.format = (NSPropertyListFormat)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue];
1371 + self.writeOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(writeOptions))] unsignedIntegerValue];
1372 +
1373 + return self;
1374 +}
1375 +
1376 +- (void)encodeWithCoder:(NSCoder *)coder {
1377 + [super encodeWithCoder:coder];
1378 +
1379 + [coder encodeInteger:self.format forKey:NSStringFromSelector(@selector(format))];
1380 + [coder encodeObject:@(self.writeOptions) forKey:NSStringFromSelector(@selector(writeOptions))];
1381 +}
1382 +
1383 +#pragma mark - NSCopying
1384 +
1385 +- (instancetype)copyWithZone:(NSZone *)zone {
1386 + AFPropertyListRequestSerializer *serializer = [super copyWithZone:zone];
1387 + serializer.format = self.format;
1388 + serializer.writeOptions = self.writeOptions;
1389 +
1390 + return serializer;
1391 +}
1392 +
1393 +@end
1 +// AFURLResponseSerialization.h
2 +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 +//
4 +// Permission is hereby granted, free of charge, to any person obtaining a copy
5 +// of this software and associated documentation files (the "Software"), to deal
6 +// in the Software without restriction, including without limitation the rights
7 +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 +// copies of the Software, and to permit persons to whom the Software is
9 +// furnished to do so, subject to the following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included in
12 +// all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 +// THE SOFTWARE.
21 +
22 +#import <Foundation/Foundation.h>
23 +#import <CoreGraphics/CoreGraphics.h>
24 +
25 +NS_ASSUME_NONNULL_BEGIN
26 +
27 +/**
28 + 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.
29 +
30 + 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.
31 + */
32 +@protocol AFURLResponseSerialization <NSObject, NSSecureCoding, NSCopying>
33 +
34 +/**
35 + The response object decoded from the data associated with a specified response.
36 +
37 + @param response The response to be processed.
38 + @param data The response data to be decoded.
39 + @param error The error that occurred while attempting to decode the response data.
40 +
41 + @return The object decoded from the specified response data.
42 + */
43 +- (nullable id)responseObjectForResponse:(nullable NSURLResponse *)response
44 + data:(nullable NSData *)data
45 + error:(NSError * _Nullable __autoreleasing *)error NS_SWIFT_NOTHROW;
46 +
47 +@end
48 +
49 +#pragma mark -
50 +
51 +/**
52 + `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.
53 +
54 + Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPResponseSerializer` in order to ensure consistent default behavior.
55 + */
56 +@interface AFHTTPResponseSerializer : NSObject <AFURLResponseSerialization>
57 +
58 +- (instancetype)init;
59 +
60 +@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.");
61 +
62 +/**
63 + Creates and returns a serializer with default configuration.
64 + */
65 ++ (instancetype)serializer;
66 +
67 +///-----------------------------------------
68 +/// @name Configuring Response Serialization
69 +///-----------------------------------------
70 +
71 +/**
72 + 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.
73 +
74 + See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
75 + */
76 +@property (nonatomic, copy, nullable) NSIndexSet *acceptableStatusCodes;
77 +
78 +/**
79 + 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.
80 + */
81 +@property (nonatomic, copy, nullable) NSSet <NSString *> *acceptableContentTypes;
82 +
83 +/**
84 + Validates the specified response and data.
85 +
86 + In its base implementation, this method checks for an acceptable status code and content type. Subclasses may wish to add other domain-specific checks.
87 +
88 + @param response The response to be validated.
89 + @param data The data associated with the response.
90 + @param error The error that occurred while attempting to validate the response.
91 +
92 + @return `YES` if the response is valid, otherwise `NO`.
93 + */
94 +- (BOOL)validateResponse:(nullable NSHTTPURLResponse *)response
95 + data:(nullable NSData *)data
96 + error:(NSError * _Nullable __autoreleasing *)error;
97 +
98 +@end
99 +
100 +#pragma mark -
101 +
102 +
103 +/**
104 + `AFJSONResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes JSON responses.
105 +
106 + By default, `AFJSONResponseSerializer` accepts the following MIME types, which includes the official standard, `application/json`, as well as other commonly-used types:
107 +
108 + - `application/json`
109 + - `text/json`
110 + - `text/javascript`
111 + */
112 +@interface AFJSONResponseSerializer : AFHTTPResponseSerializer
113 +
114 +- (instancetype)init;
115 +
116 +/**
117 + Options for reading the response JSON data and creating the Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default.
118 + */
119 +@property (nonatomic, assign) NSJSONReadingOptions readingOptions;
120 +
121 +/**
122 + Whether to remove keys with `NSNull` values from response JSON. Defaults to `NO`.
123 + */
124 +@property (nonatomic, assign) BOOL removesKeysWithNullValues;
125 +
126 +/**
127 + Creates and returns a JSON serializer with specified reading and writing options.
128 +
129 + @param readingOptions The specified JSON reading options.
130 + */
131 ++ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions;
132 +
133 +@end
134 +
135 +#pragma mark -
136 +
137 +/**
138 + `AFXMLParserResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLParser` objects.
139 +
140 + By default, `AFXMLParserResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types:
141 +
142 + - `application/xml`
143 + - `text/xml`
144 + */
145 +@interface AFXMLParserResponseSerializer : AFHTTPResponseSerializer
146 +
147 +@end
148 +
149 +#pragma mark -
150 +
151 +#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
152 +
153 +/**
154 + `AFXMLDocumentResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects.
155 +
156 + By default, `AFXMLDocumentResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types:
157 +
158 + - `application/xml`
159 + - `text/xml`
160 + */
161 +@interface AFXMLDocumentResponseSerializer : AFHTTPResponseSerializer
162 +
163 +- (instancetype)init;
164 +
165 +/**
166 + Input and output options specifically intended for `NSXMLDocument` objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default.
167 + */
168 +@property (nonatomic, assign) NSUInteger options;
169 +
170 +/**
171 + Creates and returns an XML document serializer with the specified options.
172 +
173 + @param mask The XML document options.
174 + */
175 ++ (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask;
176 +
177 +@end
178 +
179 +#endif
180 +
181 +#pragma mark -
182 +
183 +/**
184 + `AFPropertyListResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects.
185 +
186 + By default, `AFPropertyListResponseSerializer` accepts the following MIME types:
187 +
188 + - `application/x-plist`
189 + */
190 +@interface AFPropertyListResponseSerializer : AFHTTPResponseSerializer
191 +
192 +- (instancetype)init;
193 +
194 +/**
195 + The property list format. Possible values are described in "NSPropertyListFormat".
196 + */
197 +@property (nonatomic, assign) NSPropertyListFormat format;
198 +
199 +/**
200 + The property list reading options. Possible values are described in "NSPropertyListMutabilityOptions."
201 + */
202 +@property (nonatomic, assign) NSPropertyListReadOptions readOptions;
203 +
204 +/**
205 + Creates and returns a property list serializer with a specified format, read options, and write options.
206 +
207 + @param format The property list format.
208 + @param readOptions The property list reading options.
209 + */
210 ++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format
211 + readOptions:(NSPropertyListReadOptions)readOptions;
212 +
213 +@end
214 +
215 +#pragma mark -
216 +
217 +/**
218 + `AFImageResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes image responses.
219 +
220 + By default, `AFImageResponseSerializer` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage:
221 +
222 + - `image/tiff`
223 + - `image/jpeg`
224 + - `image/gif`
225 + - `image/png`
226 + - `image/ico`
227 + - `image/x-icon`
228 + - `image/bmp`
229 + - `image/x-bmp`
230 + - `image/x-xbitmap`
231 + - `image/x-win-bitmap`
232 + */
233 +@interface AFImageResponseSerializer : AFHTTPResponseSerializer
234 +
235 +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
236 +/**
237 + 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.
238 + */
239 +@property (nonatomic, assign) CGFloat imageScale;
240 +
241 +/**
242 + 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.
243 + */
244 +@property (nonatomic, assign) BOOL automaticallyInflatesResponseImage;
245 +#endif
246 +
247 +@end
248 +
249 +#pragma mark -
250 +
251 +/**
252 + `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.
253 + */
254 +@interface AFCompoundResponseSerializer : AFHTTPResponseSerializer
255 +
256 +/**
257 + The component response serializers.
258 + */
259 +@property (readonly, nonatomic, copy) NSArray <id<AFURLResponseSerialization>> *responseSerializers;
260 +
261 +/**
262 + Creates and returns a compound serializer comprised of the specified response serializers.
263 +
264 + @warning Each response serializer specified must be a subclass of `AFHTTPResponseSerializer`, and response to `-validateResponse:data:error:`.
265 + */
266 ++ (instancetype)compoundSerializerWithResponseSerializers:(NSArray <id<AFURLResponseSerialization>> *)responseSerializers;
267 +
268 +@end
269 +
270 +///----------------
271 +/// @name Constants
272 +///----------------
273 +
274 +/**
275 + ## Error Domains
276 +
277 + The following error domain is predefined.
278 +
279 + - `NSString * const AFURLResponseSerializationErrorDomain`
280 +
281 + ### Constants
282 +
283 + `AFURLResponseSerializationErrorDomain`
284 + AFURLResponseSerializer errors. Error codes for `AFURLResponseSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`.
285 + */
286 +FOUNDATION_EXPORT NSString * const AFURLResponseSerializationErrorDomain;
287 +
288 +/**
289 + ## User info dictionary keys
290 +
291 + These keys may exist in the user info dictionary, in addition to those defined for NSError.
292 +
293 + - `NSString * const AFNetworkingOperationFailingURLResponseErrorKey`
294 + - `NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey`
295 +
296 + ### Constants
297 +
298 + `AFNetworkingOperationFailingURLResponseErrorKey`
299 + The corresponding value is an `NSURLResponse` containing the response of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`.
300 +
301 + `AFNetworkingOperationFailingURLResponseDataErrorKey`
302 + 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`.
303 + */
304 +FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseErrorKey;
305 +
306 +FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey;
307 +
308 +NS_ASSUME_NONNULL_END
1 +// AFURLResponseSerialization.m
2 +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 +//
4 +// Permission is hereby granted, free of charge, to any person obtaining a copy
5 +// of this software and associated documentation files (the "Software"), to deal
6 +// in the Software without restriction, including without limitation the rights
7 +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 +// copies of the Software, and to permit persons to whom the Software is
9 +// furnished to do so, subject to the following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included in
12 +// all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 +// THE SOFTWARE.
21 +
22 +#import "AFURLResponseSerialization.h"
23 +
24 +#import <TargetConditionals.h>
25 +
26 +#if TARGET_OS_IOS
27 +#import <UIKit/UIKit.h>
28 +#elif TARGET_OS_WATCH
29 +#import <WatchKit/WatchKit.h>
30 +#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
31 +#import <Cocoa/Cocoa.h>
32 +#endif
33 +
34 +NSString * const AFURLResponseSerializationErrorDomain = @"com.alamofire.error.serialization.response";
35 +NSString * const AFNetworkingOperationFailingURLResponseErrorKey = @"com.alamofire.serialization.response.error.response";
36 +NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey = @"com.alamofire.serialization.response.error.data";
37 +
38 +static NSError * AFErrorWithUnderlyingError(NSError *error, NSError *underlyingError) {
39 + if (!error) {
40 + return underlyingError;
41 + }
42 +
43 + if (!underlyingError || error.userInfo[NSUnderlyingErrorKey]) {
44 + return error;
45 + }
46 +
47 + NSMutableDictionary *mutableUserInfo = [error.userInfo mutableCopy];
48 + mutableUserInfo[NSUnderlyingErrorKey] = underlyingError;
49 +
50 + return [[NSError alloc] initWithDomain:error.domain code:error.code userInfo:mutableUserInfo];
51 +}
52 +
53 +static BOOL AFErrorOrUnderlyingErrorHasCodeInDomain(NSError *error, NSInteger code, NSString *domain) {
54 + if ([error.domain isEqualToString:domain] && error.code == code) {
55 + return YES;
56 + } else if (error.userInfo[NSUnderlyingErrorKey]) {
57 + return AFErrorOrUnderlyingErrorHasCodeInDomain(error.userInfo[NSUnderlyingErrorKey], code, domain);
58 + }
59 +
60 + return NO;
61 +}
62 +
63 +static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingOptions readingOptions) {
64 + if ([JSONObject isKindOfClass:[NSArray class]]) {
65 + NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:[(NSArray *)JSONObject count]];
66 + for (id value in (NSArray *)JSONObject) {
67 + [mutableArray addObject:AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions)];
68 + }
69 +
70 + return (readingOptions & NSJSONReadingMutableContainers) ? mutableArray : [NSArray arrayWithArray:mutableArray];
71 + } else if ([JSONObject isKindOfClass:[NSDictionary class]]) {
72 + NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary:JSONObject];
73 + for (id <NSCopying> key in [(NSDictionary *)JSONObject allKeys]) {
74 + id value = (NSDictionary *)JSONObject[key];
75 + if (!value || [value isEqual:[NSNull null]]) {
76 + [mutableDictionary removeObjectForKey:key];
77 + } else if ([value isKindOfClass:[NSArray class]] || [value isKindOfClass:[NSDictionary class]]) {
78 + mutableDictionary[key] = AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions);
79 + }
80 + }
81 +
82 + return (readingOptions & NSJSONReadingMutableContainers) ? mutableDictionary : [NSDictionary dictionaryWithDictionary:mutableDictionary];
83 + }
84 +
85 + return JSONObject;
86 +}
87 +
88 +@implementation AFHTTPResponseSerializer
89 +
90 ++ (instancetype)serializer {
91 + return [[self alloc] init];
92 +}
93 +
94 +- (instancetype)init {
95 + self = [super init];
96 + if (!self) {
97 + return nil;
98 + }
99 +
100 + self.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)];
101 + self.acceptableContentTypes = nil;
102 +
103 + return self;
104 +}
105 +
106 +#pragma mark -
107 +
108 +- (BOOL)validateResponse:(NSHTTPURLResponse *)response
109 + data:(NSData *)data
110 + error:(NSError * __autoreleasing *)error
111 +{
112 + BOOL responseIsValid = YES;
113 + NSError *validationError = nil;
114 +
115 + if (response && [response isKindOfClass:[NSHTTPURLResponse class]]) {
116 + if (self.acceptableContentTypes && ![self.acceptableContentTypes containsObject:[response MIMEType]] &&
117 + !([response MIMEType] == nil && [data length] == 0)) {
118 +
119 + if ([data length] > 0 && [response URL]) {
120 + NSMutableDictionary *mutableUserInfo = [@{
121 + NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: unacceptable content-type: %@", @"AFNetworking", nil), [response MIMEType]],
122 + NSURLErrorFailingURLErrorKey:[response URL],
123 + AFNetworkingOperationFailingURLResponseErrorKey: response,
124 + } mutableCopy];
125 + if (data) {
126 + mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data;
127 + }
128 +
129 + validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:mutableUserInfo], validationError);
130 + }
131 +
132 + responseIsValid = NO;
133 + }
134 +
135 + if (self.acceptableStatusCodes && ![self.acceptableStatusCodes containsIndex:(NSUInteger)response.statusCode] && [response URL]) {
136 + NSMutableDictionary *mutableUserInfo = [@{
137 + NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: %@ (%ld)", @"AFNetworking", nil), [NSHTTPURLResponse localizedStringForStatusCode:response.statusCode], (long)response.statusCode],
138 + NSURLErrorFailingURLErrorKey:[response URL],
139 + AFNetworkingOperationFailingURLResponseErrorKey: response,
140 + } mutableCopy];
141 +
142 + if (data) {
143 + mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data;
144 + }
145 +
146 + validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorBadServerResponse userInfo:mutableUserInfo], validationError);
147 +
148 + responseIsValid = NO;
149 + }
150 + }
151 +
152 + if (error && !responseIsValid) {
153 + *error = validationError;
154 + }
155 +
156 + return responseIsValid;
157 +}
158 +
159 +#pragma mark - AFURLResponseSerialization
160 +
161 +- (id)responseObjectForResponse:(NSURLResponse *)response
162 + data:(NSData *)data
163 + error:(NSError *__autoreleasing *)error
164 +{
165 + [self validateResponse:(NSHTTPURLResponse *)response data:data error:error];
166 +
167 + return data;
168 +}
169 +
170 +#pragma mark - NSSecureCoding
171 +
172 ++ (BOOL)supportsSecureCoding {
173 + return YES;
174 +}
175 +
176 +- (instancetype)initWithCoder:(NSCoder *)decoder {
177 + self = [self init];
178 + if (!self) {
179 + return nil;
180 + }
181 +
182 + self.acceptableStatusCodes = [decoder decodeObjectOfClass:[NSIndexSet class] forKey:NSStringFromSelector(@selector(acceptableStatusCodes))];
183 + self.acceptableContentTypes = [decoder decodeObjectOfClass:[NSIndexSet class] forKey:NSStringFromSelector(@selector(acceptableContentTypes))];
184 +
185 + return self;
186 +}
187 +
188 +- (void)encodeWithCoder:(NSCoder *)coder {
189 + [coder encodeObject:self.acceptableStatusCodes forKey:NSStringFromSelector(@selector(acceptableStatusCodes))];
190 + [coder encodeObject:self.acceptableContentTypes forKey:NSStringFromSelector(@selector(acceptableContentTypes))];
191 +}
192 +
193 +#pragma mark - NSCopying
194 +
195 +- (instancetype)copyWithZone:(NSZone *)zone {
196 + AFHTTPResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
197 + serializer.acceptableStatusCodes = [self.acceptableStatusCodes copyWithZone:zone];
198 + serializer.acceptableContentTypes = [self.acceptableContentTypes copyWithZone:zone];
199 +
200 + return serializer;
201 +}
202 +
203 +@end
204 +
205 +#pragma mark -
206 +
207 +@implementation AFJSONResponseSerializer
208 +
209 ++ (instancetype)serializer {
210 + return [self serializerWithReadingOptions:(NSJSONReadingOptions)0];
211 +}
212 +
213 ++ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions {
214 + AFJSONResponseSerializer *serializer = [[self alloc] init];
215 + serializer.readingOptions = readingOptions;
216 +
217 + return serializer;
218 +}
219 +
220 +- (instancetype)init {
221 + self = [super init];
222 + if (!self) {
223 + return nil;
224 + }
225 +
226 + self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil];
227 +
228 + return self;
229 +}
230 +
231 +#pragma mark - AFURLResponseSerialization
232 +
233 +- (id)responseObjectForResponse:(NSURLResponse *)response
234 + data:(NSData *)data
235 + error:(NSError *__autoreleasing *)error
236 +{
237 + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
238 + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
239 + return nil;
240 + }
241 + }
242 +
243 + // 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.
244 + // See https://github.com/rails/rails/issues/1742
245 + BOOL isSpace = [data isEqualToData:[NSData dataWithBytes:" " length:1]];
246 +
247 + if (data.length == 0 || isSpace) {
248 + return nil;
249 + }
250 +
251 + NSError *serializationError = nil;
252 +
253 + id responseObject = [NSJSONSerialization JSONObjectWithData:data options:self.readingOptions error:&serializationError];
254 +
255 + if (!responseObject)
256 + {
257 + if (error) {
258 + *error = AFErrorWithUnderlyingError(serializationError, *error);
259 + }
260 + return nil;
261 + }
262 +
263 + if (self.removesKeysWithNullValues) {
264 + return AFJSONObjectByRemovingKeysWithNullValues(responseObject, self.readingOptions);
265 + }
266 +
267 + return responseObject;
268 +}
269 +
270 +#pragma mark - NSSecureCoding
271 +
272 +- (instancetype)initWithCoder:(NSCoder *)decoder {
273 + self = [super initWithCoder:decoder];
274 + if (!self) {
275 + return nil;
276 + }
277 +
278 + self.readingOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readingOptions))] unsignedIntegerValue];
279 + self.removesKeysWithNullValues = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(removesKeysWithNullValues))] boolValue];
280 +
281 + return self;
282 +}
283 +
284 +- (void)encodeWithCoder:(NSCoder *)coder {
285 + [super encodeWithCoder:coder];
286 +
287 + [coder encodeObject:@(self.readingOptions) forKey:NSStringFromSelector(@selector(readingOptions))];
288 + [coder encodeObject:@(self.removesKeysWithNullValues) forKey:NSStringFromSelector(@selector(removesKeysWithNullValues))];
289 +}
290 +
291 +#pragma mark - NSCopying
292 +
293 +- (instancetype)copyWithZone:(NSZone *)zone {
294 + AFJSONResponseSerializer *serializer = [super copyWithZone:zone];
295 + serializer.readingOptions = self.readingOptions;
296 + serializer.removesKeysWithNullValues = self.removesKeysWithNullValues;
297 +
298 + return serializer;
299 +}
300 +
301 +@end
302 +
303 +#pragma mark -
304 +
305 +@implementation AFXMLParserResponseSerializer
306 +
307 ++ (instancetype)serializer {
308 + AFXMLParserResponseSerializer *serializer = [[self alloc] init];
309 +
310 + return serializer;
311 +}
312 +
313 +- (instancetype)init {
314 + self = [super init];
315 + if (!self) {
316 + return nil;
317 + }
318 +
319 + self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil];
320 +
321 + return self;
322 +}
323 +
324 +#pragma mark - AFURLResponseSerialization
325 +
326 +- (id)responseObjectForResponse:(NSHTTPURLResponse *)response
327 + data:(NSData *)data
328 + error:(NSError *__autoreleasing *)error
329 +{
330 + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
331 + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
332 + return nil;
333 + }
334 + }
335 +
336 + return [[NSXMLParser alloc] initWithData:data];
337 +}
338 +
339 +@end
340 +
341 +#pragma mark -
342 +
343 +#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
344 +
345 +@implementation AFXMLDocumentResponseSerializer
346 +
347 ++ (instancetype)serializer {
348 + return [self serializerWithXMLDocumentOptions:0];
349 +}
350 +
351 ++ (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask {
352 + AFXMLDocumentResponseSerializer *serializer = [[self alloc] init];
353 + serializer.options = mask;
354 +
355 + return serializer;
356 +}
357 +
358 +- (instancetype)init {
359 + self = [super init];
360 + if (!self) {
361 + return nil;
362 + }
363 +
364 + self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil];
365 +
366 + return self;
367 +}
368 +
369 +#pragma mark - AFURLResponseSerialization
370 +
371 +- (id)responseObjectForResponse:(NSURLResponse *)response
372 + data:(NSData *)data
373 + error:(NSError *__autoreleasing *)error
374 +{
375 + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
376 + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
377 + return nil;
378 + }
379 + }
380 +
381 + NSError *serializationError = nil;
382 + NSXMLDocument *document = [[NSXMLDocument alloc] initWithData:data options:self.options error:&serializationError];
383 +
384 + if (!document)
385 + {
386 + if (error) {
387 + *error = AFErrorWithUnderlyingError(serializationError, *error);
388 + }
389 + return nil;
390 + }
391 +
392 + return document;
393 +}
394 +
395 +#pragma mark - NSSecureCoding
396 +
397 +- (instancetype)initWithCoder:(NSCoder *)decoder {
398 + self = [super initWithCoder:decoder];
399 + if (!self) {
400 + return nil;
401 + }
402 +
403 + self.options = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(options))] unsignedIntegerValue];
404 +
405 + return self;
406 +}
407 +
408 +- (void)encodeWithCoder:(NSCoder *)coder {
409 + [super encodeWithCoder:coder];
410 +
411 + [coder encodeObject:@(self.options) forKey:NSStringFromSelector(@selector(options))];
412 +}
413 +
414 +#pragma mark - NSCopying
415 +
416 +- (instancetype)copyWithZone:(NSZone *)zone {
417 + AFXMLDocumentResponseSerializer *serializer = [super copyWithZone:zone];
418 + serializer.options = self.options;
419 +
420 + return serializer;
421 +}
422 +
423 +@end
424 +
425 +#endif
426 +
427 +#pragma mark -
428 +
429 +@implementation AFPropertyListResponseSerializer
430 +
431 ++ (instancetype)serializer {
432 + return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 readOptions:0];
433 +}
434 +
435 ++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format
436 + readOptions:(NSPropertyListReadOptions)readOptions
437 +{
438 + AFPropertyListResponseSerializer *serializer = [[self alloc] init];
439 + serializer.format = format;
440 + serializer.readOptions = readOptions;
441 +
442 + return serializer;
443 +}
444 +
445 +- (instancetype)init {
446 + self = [super init];
447 + if (!self) {
448 + return nil;
449 + }
450 +
451 + self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/x-plist", nil];
452 +
453 + return self;
454 +}
455 +
456 +#pragma mark - AFURLResponseSerialization
457 +
458 +- (id)responseObjectForResponse:(NSURLResponse *)response
459 + data:(NSData *)data
460 + error:(NSError *__autoreleasing *)error
461 +{
462 + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
463 + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
464 + return nil;
465 + }
466 + }
467 +
468 + if (!data) {
469 + return nil;
470 + }
471 +
472 + NSError *serializationError = nil;
473 +
474 + id responseObject = [NSPropertyListSerialization propertyListWithData:data options:self.readOptions format:NULL error:&serializationError];
475 +
476 + if (!responseObject)
477 + {
478 + if (error) {
479 + *error = AFErrorWithUnderlyingError(serializationError, *error);
480 + }
481 + return nil;
482 + }
483 +
484 + return responseObject;
485 +}
486 +
487 +#pragma mark - NSSecureCoding
488 +
489 +- (instancetype)initWithCoder:(NSCoder *)decoder {
490 + self = [super initWithCoder:decoder];
491 + if (!self) {
492 + return nil;
493 + }
494 +
495 + self.format = (NSPropertyListFormat)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue];
496 + self.readOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readOptions))] unsignedIntegerValue];
497 +
498 + return self;
499 +}
500 +
501 +- (void)encodeWithCoder:(NSCoder *)coder {
502 + [super encodeWithCoder:coder];
503 +
504 + [coder encodeObject:@(self.format) forKey:NSStringFromSelector(@selector(format))];
505 + [coder encodeObject:@(self.readOptions) forKey:NSStringFromSelector(@selector(readOptions))];
506 +}
507 +
508 +#pragma mark - NSCopying
509 +
510 +- (instancetype)copyWithZone:(NSZone *)zone {
511 + AFPropertyListResponseSerializer *serializer = [super copyWithZone:zone];
512 + serializer.format = self.format;
513 + serializer.readOptions = self.readOptions;
514 +
515 + return serializer;
516 +}
517 +
518 +@end
519 +
520 +#pragma mark -
521 +
522 +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
523 +#import <CoreGraphics/CoreGraphics.h>
524 +#import <UIKit/UIKit.h>
525 +
526 +@interface UIImage (AFNetworkingSafeImageLoading)
527 ++ (UIImage *)af_safeImageWithData:(NSData *)data;
528 +@end
529 +
530 +static NSLock* imageLock = nil;
531 +
532 +@implementation UIImage (AFNetworkingSafeImageLoading)
533 +
534 ++ (UIImage *)af_safeImageWithData:(NSData *)data {
535 + UIImage* image = nil;
536 + static dispatch_once_t onceToken;
537 + dispatch_once(&onceToken, ^{
538 + imageLock = [[NSLock alloc] init];
539 + });
540 +
541 + [imageLock lock];
542 + image = [UIImage imageWithData:data];
543 + [imageLock unlock];
544 + return image;
545 +}
546 +
547 +@end
548 +
549 +static UIImage * AFImageWithDataAtScale(NSData *data, CGFloat scale) {
550 + UIImage *image = [UIImage af_safeImageWithData:data];
551 + if (image.images) {
552 + return image;
553 + }
554 +
555 + return [[UIImage alloc] initWithCGImage:[image CGImage] scale:scale orientation:image.imageOrientation];
556 +}
557 +
558 +static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *response, NSData *data, CGFloat scale) {
559 + if (!data || [data length] == 0) {
560 + return nil;
561 + }
562 +
563 + CGImageRef imageRef = NULL;
564 + CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data);
565 +
566 + if ([response.MIMEType isEqualToString:@"image/png"]) {
567 + imageRef = CGImageCreateWithPNGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault);
568 + } else if ([response.MIMEType isEqualToString:@"image/jpeg"]) {
569 + imageRef = CGImageCreateWithJPEGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault);
570 +
571 + if (imageRef) {
572 + CGColorSpaceRef imageColorSpace = CGImageGetColorSpace(imageRef);
573 + CGColorSpaceModel imageColorSpaceModel = CGColorSpaceGetModel(imageColorSpace);
574 +
575 + // CGImageCreateWithJPEGDataProvider does not properly handle CMKY, so fall back to AFImageWithDataAtScale
576 + if (imageColorSpaceModel == kCGColorSpaceModelCMYK) {
577 + CGImageRelease(imageRef);
578 + imageRef = NULL;
579 + }
580 + }
581 + }
582 +
583 + CGDataProviderRelease(dataProvider);
584 +
585 + UIImage *image = AFImageWithDataAtScale(data, scale);
586 + if (!imageRef) {
587 + if (image.images || !image) {
588 + return image;
589 + }
590 +
591 + imageRef = CGImageCreateCopy([image CGImage]);
592 + if (!imageRef) {
593 + return nil;
594 + }
595 + }
596 +
597 + size_t width = CGImageGetWidth(imageRef);
598 + size_t height = CGImageGetHeight(imageRef);
599 + size_t bitsPerComponent = CGImageGetBitsPerComponent(imageRef);
600 +
601 + if (width * height > 1024 * 1024 || bitsPerComponent > 8) {
602 + CGImageRelease(imageRef);
603 +
604 + return image;
605 + }
606 +
607 + // CGImageGetBytesPerRow() calculates incorrectly in iOS 5.0, so defer to CGBitmapContextCreate
608 + size_t bytesPerRow = 0;
609 + CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
610 + CGColorSpaceModel colorSpaceModel = CGColorSpaceGetModel(colorSpace);
611 + CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
612 +
613 + if (colorSpaceModel == kCGColorSpaceModelRGB) {
614 + uint32_t alpha = (bitmapInfo & kCGBitmapAlphaInfoMask);
615 +#pragma clang diagnostic push
616 +#pragma clang diagnostic ignored "-Wassign-enum"
617 + if (alpha == kCGImageAlphaNone) {
618 + bitmapInfo &= ~kCGBitmapAlphaInfoMask;
619 + bitmapInfo |= kCGImageAlphaNoneSkipFirst;
620 + } else if (!(alpha == kCGImageAlphaNoneSkipFirst || alpha == kCGImageAlphaNoneSkipLast)) {
621 + bitmapInfo &= ~kCGBitmapAlphaInfoMask;
622 + bitmapInfo |= kCGImageAlphaPremultipliedFirst;
623 + }
624 +#pragma clang diagnostic pop
625 + }
626 +
627 + CGContextRef context = CGBitmapContextCreate(NULL, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo);
628 +
629 + CGColorSpaceRelease(colorSpace);
630 +
631 + if (!context) {
632 + CGImageRelease(imageRef);
633 +
634 + return image;
635 + }
636 +
637 + CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, width, height), imageRef);
638 + CGImageRef inflatedImageRef = CGBitmapContextCreateImage(context);
639 +
640 + CGContextRelease(context);
641 +
642 + UIImage *inflatedImage = [[UIImage alloc] initWithCGImage:inflatedImageRef scale:scale orientation:image.imageOrientation];
643 +
644 + CGImageRelease(inflatedImageRef);
645 + CGImageRelease(imageRef);
646 +
647 + return inflatedImage;
648 +}
649 +#endif
650 +
651 +
652 +@implementation AFImageResponseSerializer
653 +
654 +- (instancetype)init {
655 + self = [super init];
656 + if (!self) {
657 + return nil;
658 + }
659 +
660 + 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];
661 +
662 +#if TARGET_OS_IOS || TARGET_OS_TV
663 + self.imageScale = [[UIScreen mainScreen] scale];
664 + self.automaticallyInflatesResponseImage = YES;
665 +#elif TARGET_OS_WATCH
666 + self.imageScale = [[WKInterfaceDevice currentDevice] screenScale];
667 + self.automaticallyInflatesResponseImage = YES;
668 +#endif
669 +
670 + return self;
671 +}
672 +
673 +#pragma mark - AFURLResponseSerializer
674 +
675 +- (id)responseObjectForResponse:(NSURLResponse *)response
676 + data:(NSData *)data
677 + error:(NSError *__autoreleasing *)error
678 +{
679 + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
680 + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
681 + return nil;
682 + }
683 + }
684 +
685 +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
686 + if (self.automaticallyInflatesResponseImage) {
687 + return AFInflatedImageFromResponseWithDataAtScale((NSHTTPURLResponse *)response, data, self.imageScale);
688 + } else {
689 + return AFImageWithDataAtScale(data, self.imageScale);
690 + }
691 +#else
692 + // Ensure that the image is set to it's correct pixel width and height
693 + NSBitmapImageRep *bitimage = [[NSBitmapImageRep alloc] initWithData:data];
694 + NSImage *image = [[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])];
695 + [image addRepresentation:bitimage];
696 +
697 + return image;
698 +#endif
699 +
700 + return nil;
701 +}
702 +
703 +#pragma mark - NSSecureCoding
704 +
705 +- (instancetype)initWithCoder:(NSCoder *)decoder {
706 + self = [super initWithCoder:decoder];
707 + if (!self) {
708 + return nil;
709 + }
710 +
711 +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
712 + NSNumber *imageScale = [decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(imageScale))];
713 +#if CGFLOAT_IS_DOUBLE
714 + self.imageScale = [imageScale doubleValue];
715 +#else
716 + self.imageScale = [imageScale floatValue];
717 +#endif
718 +
719 + self.automaticallyInflatesResponseImage = [decoder decodeBoolForKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))];
720 +#endif
721 +
722 + return self;
723 +}
724 +
725 +- (void)encodeWithCoder:(NSCoder *)coder {
726 + [super encodeWithCoder:coder];
727 +
728 +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
729 + [coder encodeObject:@(self.imageScale) forKey:NSStringFromSelector(@selector(imageScale))];
730 + [coder encodeBool:self.automaticallyInflatesResponseImage forKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))];
731 +#endif
732 +}
733 +
734 +#pragma mark - NSCopying
735 +
736 +- (instancetype)copyWithZone:(NSZone *)zone {
737 + AFImageResponseSerializer *serializer = [super copyWithZone:zone];
738 +
739 +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
740 + serializer.imageScale = self.imageScale;
741 + serializer.automaticallyInflatesResponseImage = self.automaticallyInflatesResponseImage;
742 +#endif
743 +
744 + return serializer;
745 +}
746 +
747 +@end
748 +
749 +#pragma mark -
750 +
751 +@interface AFCompoundResponseSerializer ()
752 +@property (readwrite, nonatomic, copy) NSArray *responseSerializers;
753 +@end
754 +
755 +@implementation AFCompoundResponseSerializer
756 +
757 ++ (instancetype)compoundSerializerWithResponseSerializers:(NSArray *)responseSerializers {
758 + AFCompoundResponseSerializer *serializer = [[self alloc] init];
759 + serializer.responseSerializers = responseSerializers;
760 +
761 + return serializer;
762 +}
763 +
764 +#pragma mark - AFURLResponseSerialization
765 +
766 +- (id)responseObjectForResponse:(NSURLResponse *)response
767 + data:(NSData *)data
768 + error:(NSError *__autoreleasing *)error
769 +{
770 + for (id <AFURLResponseSerialization> serializer in self.responseSerializers) {
771 + if (![serializer isKindOfClass:[AFHTTPResponseSerializer class]]) {
772 + continue;
773 + }
774 +
775 + NSError *serializerError = nil;
776 + id responseObject = [serializer responseObjectForResponse:response data:data error:&serializerError];
777 + if (responseObject) {
778 + if (error) {
779 + *error = AFErrorWithUnderlyingError(serializerError, *error);
780 + }
781 +
782 + return responseObject;
783 + }
784 + }
785 +
786 + return [super responseObjectForResponse:response data:data error:error];
787 +}
788 +
789 +#pragma mark - NSSecureCoding
790 +
791 +- (instancetype)initWithCoder:(NSCoder *)decoder {
792 + self = [super initWithCoder:decoder];
793 + if (!self) {
794 + return nil;
795 + }
796 +
797 + self.responseSerializers = [decoder decodeObjectOfClass:[NSArray class] forKey:NSStringFromSelector(@selector(responseSerializers))];
798 +
799 + return self;
800 +}
801 +
802 +- (void)encodeWithCoder:(NSCoder *)coder {
803 + [super encodeWithCoder:coder];
804 +
805 + [coder encodeObject:self.responseSerializers forKey:NSStringFromSelector(@selector(responseSerializers))];
806 +}
807 +
808 +#pragma mark - NSCopying
809 +
810 +- (instancetype)copyWithZone:(NSZone *)zone {
811 + AFCompoundResponseSerializer *serializer = [super copyWithZone:zone];
812 + serializer.responseSerializers = self.responseSerializers;
813 +
814 + return serializer;
815 +}
816 +
817 +@end
1 +// AFURLSessionManager.h
2 +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 +//
4 +// Permission is hereby granted, free of charge, to any person obtaining a copy
5 +// of this software and associated documentation files (the "Software"), to deal
6 +// in the Software without restriction, including without limitation the rights
7 +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 +// copies of the Software, and to permit persons to whom the Software is
9 +// furnished to do so, subject to the following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included in
12 +// all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 +// THE SOFTWARE.
21 +
22 +
23 +#import <Foundation/Foundation.h>
24 +
25 +#import "AFURLResponseSerialization.h"
26 +#import "AFURLRequestSerialization.h"
27 +#import "AFSecurityPolicy.h"
28 +#if !TARGET_OS_WATCH
29 +#import "AFNetworkReachabilityManager.h"
30 +#endif
31 +
32 +/**
33 + `AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to `<NSURLSessionTaskDelegate>`, `<NSURLSessionDataDelegate>`, `<NSURLSessionDownloadDelegate>`, and `<NSURLSessionDelegate>`.
34 +
35 + ## Subclassing Notes
36 +
37 + 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.
38 +
39 + ## NSURLSession & NSURLSessionTask Delegate Methods
40 +
41 + `AFURLSessionManager` implements the following delegate methods:
42 +
43 + ### `NSURLSessionDelegate`
44 +
45 + - `URLSession:didBecomeInvalidWithError:`
46 + - `URLSession:didReceiveChallenge:completionHandler:`
47 + - `URLSessionDidFinishEventsForBackgroundURLSession:`
48 +
49 + ### `NSURLSessionTaskDelegate`
50 +
51 + - `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:`
52 + - `URLSession:task:didReceiveChallenge:completionHandler:`
53 + - `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`
54 + - `URLSession:task:needNewBodyStream:`
55 + - `URLSession:task:didCompleteWithError:`
56 +
57 + ### `NSURLSessionDataDelegate`
58 +
59 + - `URLSession:dataTask:didReceiveResponse:completionHandler:`
60 + - `URLSession:dataTask:didBecomeDownloadTask:`
61 + - `URLSession:dataTask:didReceiveData:`
62 + - `URLSession:dataTask:willCacheResponse:completionHandler:`
63 +
64 + ### `NSURLSessionDownloadDelegate`
65 +
66 + - `URLSession:downloadTask:didFinishDownloadingToURL:`
67 + - `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesWritten:totalBytesExpectedToWrite:`
68 + - `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`
69 +
70 + If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first.
71 +
72 + ## Network Reachability Monitoring
73 +
74 + 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.
75 +
76 + ## NSCoding Caveats
77 +
78 + - Encoded managers do not include any block properties. Be sure to set delegate callback blocks when using `-initWithCoder:` or `NSKeyedUnarchiver`.
79 +
80 + ## NSCopying Caveats
81 +
82 + - `-copy` and `-copyWithZone:` return a new manager with a new `NSURLSession` created from the configuration of the original.
83 + - 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.
84 +
85 + @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.
86 + */
87 +
88 +NS_ASSUME_NONNULL_BEGIN
89 +
90 +@interface AFURLSessionManager : NSObject <NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate, NSSecureCoding, NSCopying>
91 +
92 +/**
93 + The managed session.
94 + */
95 +@property (readonly, nonatomic, strong) NSURLSession *session;
96 +
97 +/**
98 + The operation queue on which delegate callbacks are run.
99 + */
100 +@property (readonly, nonatomic, strong) NSOperationQueue *operationQueue;
101 +
102 +/**
103 + 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`.
104 +
105 + @warning `responseSerializer` must not be `nil`.
106 + */
107 +@property (nonatomic, strong) id <AFURLResponseSerialization> responseSerializer;
108 +
109 +///-------------------------------
110 +/// @name Managing Security Policy
111 +///-------------------------------
112 +
113 +/**
114 + The security policy used by created session to evaluate server trust for secure connections. `AFURLSessionManager` uses the `defaultPolicy` unless otherwise specified.
115 + */
116 +@property (nonatomic, strong) AFSecurityPolicy *securityPolicy;
117 +
118 +#if !TARGET_OS_WATCH
119 +///--------------------------------------
120 +/// @name Monitoring Network Reachability
121 +///--------------------------------------
122 +
123 +/**
124 + The network reachability manager. `AFURLSessionManager` uses the `sharedManager` by default.
125 + */
126 +@property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager;
127 +#endif
128 +
129 +///----------------------------
130 +/// @name Getting Session Tasks
131 +///----------------------------
132 +
133 +/**
134 + The data, upload, and download tasks currently run by the managed session.
135 + */
136 +@property (readonly, nonatomic, strong) NSArray <NSURLSessionTask *> *tasks;
137 +
138 +/**
139 + The data tasks currently run by the managed session.
140 + */
141 +@property (readonly, nonatomic, strong) NSArray <NSURLSessionDataTask *> *dataTasks;
142 +
143 +/**
144 + The upload tasks currently run by the managed session.
145 + */
146 +@property (readonly, nonatomic, strong) NSArray <NSURLSessionUploadTask *> *uploadTasks;
147 +
148 +/**
149 + The download tasks currently run by the managed session.
150 + */
151 +@property (readonly, nonatomic, strong) NSArray <NSURLSessionDownloadTask *> *downloadTasks;
152 +
153 +///-------------------------------
154 +/// @name Managing Callback Queues
155 +///-------------------------------
156 +
157 +/**
158 + The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used.
159 + */
160 +@property (nonatomic, strong, nullable) dispatch_queue_t completionQueue;
161 +
162 +/**
163 + The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used.
164 + */
165 +@property (nonatomic, strong, nullable) dispatch_group_t completionGroup;
166 +
167 +///---------------------------------
168 +/// @name Working Around System Bugs
169 +///---------------------------------
170 +
171 +/**
172 + Whether to attempt to retry creation of upload tasks for background sessions when initial call returns `nil`. `NO` by default.
173 +
174 + @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.
175 +
176 + @see https://github.com/AFNetworking/AFNetworking/issues/1675
177 + */
178 +@property (nonatomic, assign) BOOL attemptsToRecreateUploadTasksForBackgroundSessions;
179 +
180 +///---------------------
181 +/// @name Initialization
182 +///---------------------
183 +
184 +/**
185 + Creates and returns a manager for a session created with the specified configuration. This is the designated initializer.
186 +
187 + @param configuration The configuration used to create the managed session.
188 +
189 + @return A manager for a newly-created session.
190 + */
191 +- (instancetype)initWithSessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER;
192 +
193 +/**
194 + Invalidates the managed session, optionally canceling pending tasks.
195 +
196 + @param cancelPendingTasks Whether or not to cancel pending tasks.
197 + */
198 +- (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks;
199 +
200 +///-------------------------
201 +/// @name Running Data Tasks
202 +///-------------------------
203 +
204 +/**
205 + Creates an `NSURLSessionDataTask` with the specified request.
206 +
207 + @param request The HTTP request for the request.
208 + @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.
209 + */
210 +- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
211 + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler DEPRECATED_ATTRIBUTE;
212 +
213 +/**
214 + Creates an `NSURLSessionDataTask` with the specified request.
215 +
216 + @param request The HTTP request for the request.
217 + @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.
218 + @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.
219 + @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.
220 + */
221 +- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
222 + uploadProgress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock
223 + downloadProgress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock
224 + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler;
225 +
226 +///---------------------------
227 +/// @name Running Upload Tasks
228 +///---------------------------
229 +
230 +/**
231 + Creates an `NSURLSessionUploadTask` with the specified request for a local file.
232 +
233 + @param request The HTTP request for the request.
234 + @param fileURL A URL to the local file to be uploaded.
235 + @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.
236 + @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.
237 +
238 + @see `attemptsToRecreateUploadTasksForBackgroundSessions`
239 + */
240 +- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
241 + fromFile:(NSURL *)fileURL
242 + progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock
243 + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler;
244 +
245 +/**
246 + Creates an `NSURLSessionUploadTask` with the specified request for an HTTP body.
247 +
248 + @param request The HTTP request for the request.
249 + @param bodyData A data object containing the HTTP body to be uploaded.
250 + @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.
251 + @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.
252 + */
253 +- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
254 + fromData:(nullable NSData *)bodyData
255 + progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock
256 + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler;
257 +
258 +/**
259 + Creates an `NSURLSessionUploadTask` with the specified streaming request.
260 +
261 + @param request The HTTP request for the request.
262 + @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.
263 + @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.
264 + */
265 +- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request
266 + progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock
267 + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler;
268 +
269 +///-----------------------------
270 +/// @name Running Download Tasks
271 +///-----------------------------
272 +
273 +/**
274 + Creates an `NSURLSessionDownloadTask` with the specified request.
275 +
276 + @param request The HTTP request for the request.
277 + @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.
278 + @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.
279 + @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.
280 +
281 + @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.
282 + */
283 +- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request
284 + progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock
285 + destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
286 + completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * _Nullable filePath, NSError * _Nullable error))completionHandler;
287 +
288 +/**
289 + Creates an `NSURLSessionDownloadTask` with the specified resume data.
290 +
291 + @param resumeData The data used to resume downloading.
292 + @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.
293 + @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.
294 + @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.
295 + */
296 +- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData
297 + progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock
298 + destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
299 + completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * _Nullable filePath, NSError * _Nullable error))completionHandler;
300 +
301 +///---------------------------------
302 +/// @name Getting Progress for Tasks
303 +///---------------------------------
304 +
305 +/**
306 + Returns the upload progress of the specified task.
307 +
308 + @param task The session task. Must not be `nil`.
309 +
310 + @return An `NSProgress` object reporting the upload progress of a task, or `nil` if the progress is unavailable.
311 + */
312 +- (nullable NSProgress *)uploadProgressForTask:(NSURLSessionTask *)task;
313 +
314 +/**
315 + Returns the download progress of the specified task.
316 +
317 + @param task The session task. Must not be `nil`.
318 +
319 + @return An `NSProgress` object reporting the download progress of a task, or `nil` if the progress is unavailable.
320 + */
321 +- (nullable NSProgress *)downloadProgressForTask:(NSURLSessionTask *)task;
322 +
323 +///-----------------------------------------
324 +/// @name Setting Session Delegate Callbacks
325 +///-----------------------------------------
326 +
327 +/**
328 + Sets a block to be executed when the managed session becomes invalid, as handled by the `NSURLSessionDelegate` method `URLSession:didBecomeInvalidWithError:`.
329 +
330 + @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.
331 + */
332 +- (void)setSessionDidBecomeInvalidBlock:(nullable void (^)(NSURLSession *session, NSError *error))block;
333 +
334 +/**
335 + Sets a block to be executed when a connection level authentication challenge has occurred, as handled by the `NSURLSessionDelegate` method `URLSession:didReceiveChallenge:completionHandler:`.
336 +
337 + @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.
338 + */
339 +- (void)setSessionDidReceiveAuthenticationChallengeBlock:(nullable NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * _Nullable __autoreleasing * _Nullable credential))block;
340 +
341 +///--------------------------------------
342 +/// @name Setting Task Delegate Callbacks
343 +///--------------------------------------
344 +
345 +/**
346 + 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:`.
347 +
348 + @param block A block object to be executed when a task requires a new request body stream.
349 + */
350 +- (void)setTaskNeedNewBodyStreamBlock:(nullable NSInputStream * (^)(NSURLSession *session, NSURLSessionTask *task))block;
351 +
352 +/**
353 + 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:`.
354 +
355 + @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.
356 + */
357 +- (void)setTaskWillPerformHTTPRedirectionBlock:(nullable NSURLRequest * (^)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request))block;
358 +
359 +/**
360 + 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:`.
361 +
362 + @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.
363 + */
364 +- (void)setTaskDidReceiveAuthenticationChallengeBlock:(nullable NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * _Nullable __autoreleasing * _Nullable credential))block;
365 +
366 +/**
367 + Sets a block to be executed periodically to track upload progress, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`.
368 +
369 + @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.
370 + */
371 +- (void)setTaskDidSendBodyDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))block;
372 +
373 +/**
374 + Sets a block to be executed as the last message related to a specific task, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didCompleteWithError:`.
375 +
376 + @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.
377 + */
378 +- (void)setTaskDidCompleteBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, NSError * _Nullable error))block;
379 +
380 +///-------------------------------------------
381 +/// @name Setting Data Task Delegate Callbacks
382 +///-------------------------------------------
383 +
384 +/**
385 + Sets a block to be executed when a data task has received a response, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveResponse:completionHandler:`.
386 +
387 + @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.
388 + */
389 +- (void)setDataTaskDidReceiveResponseBlock:(nullable NSURLSessionResponseDisposition (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response))block;
390 +
391 +/**
392 + Sets a block to be executed when a data task has become a download task, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didBecomeDownloadTask:`.
393 +
394 + @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.
395 + */
396 +- (void)setDataTaskDidBecomeDownloadTaskBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask))block;
397 +
398 +/**
399 + Sets a block to be executed when a data task receives data, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveData:`.
400 +
401 + @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.
402 + */
403 +- (void)setDataTaskDidReceiveDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data))block;
404 +
405 +/**
406 + 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:`.
407 +
408 + @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.
409 + */
410 +- (void)setDataTaskWillCacheResponseBlock:(nullable NSCachedURLResponse * (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse))block;
411 +
412 +/**
413 + Sets a block to be executed once all messages enqueued for a session have been delivered, as handled by the `NSURLSessionDataDelegate` method `URLSessionDidFinishEventsForBackgroundURLSession:`.
414 +
415 + @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.
416 + */
417 +- (void)setDidFinishEventsForBackgroundURLSessionBlock:(nullable void (^)(NSURLSession *session))block;
418 +
419 +///-----------------------------------------------
420 +/// @name Setting Download Task Delegate Callbacks
421 +///-----------------------------------------------
422 +
423 +/**
424 + Sets a block to be executed when a download task has completed a download, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didFinishDownloadingToURL:`.
425 +
426 + @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.
427 + */
428 +- (void)setDownloadTaskDidFinishDownloadingBlock:(nullable NSURL * _Nullable (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block;
429 +
430 +/**
431 + Sets a block to be executed periodically to track download progress, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesWritten:totalBytesExpectedToWrite:`.
432 +
433 + @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.
434 + */
435 +- (void)setDownloadTaskDidWriteDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite))block;
436 +
437 +/**
438 + Sets a block to be executed when a download task has been resumed, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`.
439 +
440 + @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.
441 + */
442 +- (void)setDownloadTaskDidResumeBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes))block;
443 +
444 +@end
445 +
446 +///--------------------
447 +/// @name Notifications
448 +///--------------------
449 +
450 +/**
451 + Posted when a task resumes.
452 + */
453 +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidResumeNotification;
454 +
455 +/**
456 + Posted when a task finishes executing. Includes a userInfo dictionary with additional information about the task.
457 + */
458 +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteNotification;
459 +
460 +/**
461 + Posted when a task suspends its execution.
462 + */
463 +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidSuspendNotification;
464 +
465 +/**
466 + Posted when a session is invalidated.
467 + */
468 +FOUNDATION_EXPORT NSString * const AFURLSessionDidInvalidateNotification;
469 +
470 +/**
471 + Posted when a session download task encountered an error when moving the temporary download file to a specified destination.
472 + */
473 +FOUNDATION_EXPORT NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification;
474 +
475 +/**
476 + The raw response data of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if response data exists for the task.
477 + */
478 +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteResponseDataKey;
479 +
480 +/**
481 + The serialized response object of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if the response was serialized.
482 + */
483 +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey;
484 +
485 +/**
486 + The response serializer used to serialize the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if the task has an associated response serializer.
487 + */
488 +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey;
489 +
490 +/**
491 + 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.
492 + */
493 +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteAssetPathKey;
494 +
495 +/**
496 + Any error associated with the task, or the serialization of the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if an error exists.
497 + */
498 +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteErrorKey;
499 +
500 +NS_ASSUME_NONNULL_END
1 +// AFURLSessionManager.m
2 +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 +//
4 +// Permission is hereby granted, free of charge, to any person obtaining a copy
5 +// of this software and associated documentation files (the "Software"), to deal
6 +// in the Software without restriction, including without limitation the rights
7 +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 +// copies of the Software, and to permit persons to whom the Software is
9 +// furnished to do so, subject to the following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included in
12 +// all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 +// THE SOFTWARE.
21 +
22 +#import "AFURLSessionManager.h"
23 +#import <objc/runtime.h>
24 +
25 +#ifndef NSFoundationVersionNumber_iOS_8_0
26 +#define NSFoundationVersionNumber_With_Fixed_5871104061079552_bug 1140.11
27 +#else
28 +#define NSFoundationVersionNumber_With_Fixed_5871104061079552_bug NSFoundationVersionNumber_iOS_8_0
29 +#endif
30 +
31 +static dispatch_queue_t url_session_manager_creation_queue() {
32 + static dispatch_queue_t af_url_session_manager_creation_queue;
33 + static dispatch_once_t onceToken;
34 + dispatch_once(&onceToken, ^{
35 + af_url_session_manager_creation_queue = dispatch_queue_create("com.alamofire.networking.session.manager.creation", DISPATCH_QUEUE_SERIAL);
36 + });
37 +
38 + return af_url_session_manager_creation_queue;
39 +}
40 +
41 +static void url_session_manager_create_task_safely(dispatch_block_t block) {
42 + if (NSFoundationVersionNumber < NSFoundationVersionNumber_With_Fixed_5871104061079552_bug) {
43 + // Fix of bug
44 + // Open Radar:http://openradar.appspot.com/radar?id=5871104061079552 (status: Fixed in iOS8)
45 + // Issue about:https://github.com/AFNetworking/AFNetworking/issues/2093
46 + dispatch_sync(url_session_manager_creation_queue(), block);
47 + } else {
48 + block();
49 + }
50 +}
51 +
52 +static dispatch_queue_t url_session_manager_processing_queue() {
53 + static dispatch_queue_t af_url_session_manager_processing_queue;
54 + static dispatch_once_t onceToken;
55 + dispatch_once(&onceToken, ^{
56 + af_url_session_manager_processing_queue = dispatch_queue_create("com.alamofire.networking.session.manager.processing", DISPATCH_QUEUE_CONCURRENT);
57 + });
58 +
59 + return af_url_session_manager_processing_queue;
60 +}
61 +
62 +static dispatch_group_t url_session_manager_completion_group() {
63 + static dispatch_group_t af_url_session_manager_completion_group;
64 + static dispatch_once_t onceToken;
65 + dispatch_once(&onceToken, ^{
66 + af_url_session_manager_completion_group = dispatch_group_create();
67 + });
68 +
69 + return af_url_session_manager_completion_group;
70 +}
71 +
72 +NSString * const AFNetworkingTaskDidResumeNotification = @"com.alamofire.networking.task.resume";
73 +NSString * const AFNetworkingTaskDidCompleteNotification = @"com.alamofire.networking.task.complete";
74 +NSString * const AFNetworkingTaskDidSuspendNotification = @"com.alamofire.networking.task.suspend";
75 +NSString * const AFURLSessionDidInvalidateNotification = @"com.alamofire.networking.session.invalidate";
76 +NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification = @"com.alamofire.networking.session.download.file-manager-error";
77 +
78 +NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey = @"com.alamofire.networking.task.complete.serializedresponse";
79 +NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey = @"com.alamofire.networking.task.complete.responseserializer";
80 +NSString * const AFNetworkingTaskDidCompleteResponseDataKey = @"com.alamofire.networking.complete.finish.responsedata";
81 +NSString * const AFNetworkingTaskDidCompleteErrorKey = @"com.alamofire.networking.task.complete.error";
82 +NSString * const AFNetworkingTaskDidCompleteAssetPathKey = @"com.alamofire.networking.task.complete.assetpath";
83 +
84 +static NSString * const AFURLSessionManagerLockName = @"com.alamofire.networking.session.manager.lock";
85 +
86 +static NSUInteger const AFMaximumNumberOfAttemptsToRecreateBackgroundSessionUploadTask = 3;
87 +
88 +typedef void (^AFURLSessionDidBecomeInvalidBlock)(NSURLSession *session, NSError *error);
89 +typedef NSURLSessionAuthChallengeDisposition (^AFURLSessionDidReceiveAuthenticationChallengeBlock)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential);
90 +
91 +typedef NSURLRequest * (^AFURLSessionTaskWillPerformHTTPRedirectionBlock)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request);
92 +typedef NSURLSessionAuthChallengeDisposition (^AFURLSessionTaskDidReceiveAuthenticationChallengeBlock)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential);
93 +typedef void (^AFURLSessionDidFinishEventsForBackgroundURLSessionBlock)(NSURLSession *session);
94 +
95 +typedef NSInputStream * (^AFURLSessionTaskNeedNewBodyStreamBlock)(NSURLSession *session, NSURLSessionTask *task);
96 +typedef void (^AFURLSessionTaskDidSendBodyDataBlock)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend);
97 +typedef void (^AFURLSessionTaskDidCompleteBlock)(NSURLSession *session, NSURLSessionTask *task, NSError *error);
98 +
99 +typedef NSURLSessionResponseDisposition (^AFURLSessionDataTaskDidReceiveResponseBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response);
100 +typedef void (^AFURLSessionDataTaskDidBecomeDownloadTaskBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask);
101 +typedef void (^AFURLSessionDataTaskDidReceiveDataBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data);
102 +typedef NSCachedURLResponse * (^AFURLSessionDataTaskWillCacheResponseBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse);
103 +
104 +typedef NSURL * (^AFURLSessionDownloadTaskDidFinishDownloadingBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location);
105 +typedef void (^AFURLSessionDownloadTaskDidWriteDataBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite);
106 +typedef void (^AFURLSessionDownloadTaskDidResumeBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes);
107 +typedef void (^AFURLSessionTaskProgressBlock)(NSProgress *);
108 +
109 +typedef void (^AFURLSessionTaskCompletionHandler)(NSURLResponse *response, id responseObject, NSError *error);
110 +
111 +
112 +#pragma mark -
113 +
114 +@interface AFURLSessionManagerTaskDelegate : NSObject <NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate>
115 +- (instancetype)initWithTask:(NSURLSessionTask *)task;
116 +@property (nonatomic, weak) AFURLSessionManager *manager;
117 +@property (nonatomic, strong) NSMutableData *mutableData;
118 +@property (nonatomic, strong) NSProgress *uploadProgress;
119 +@property (nonatomic, strong) NSProgress *downloadProgress;
120 +@property (nonatomic, copy) NSURL *downloadFileURL;
121 +@property (nonatomic, copy) AFURLSessionDownloadTaskDidFinishDownloadingBlock downloadTaskDidFinishDownloading;
122 +@property (nonatomic, copy) AFURLSessionTaskProgressBlock uploadProgressBlock;
123 +@property (nonatomic, copy) AFURLSessionTaskProgressBlock downloadProgressBlock;
124 +@property (nonatomic, copy) AFURLSessionTaskCompletionHandler completionHandler;
125 +@end
126 +
127 +@implementation AFURLSessionManagerTaskDelegate
128 +
129 +- (instancetype)initWithTask:(NSURLSessionTask *)task {
130 + self = [super init];
131 + if (!self) {
132 + return nil;
133 + }
134 +
135 + _mutableData = [NSMutableData data];
136 + _uploadProgress = [[NSProgress alloc] initWithParent:nil userInfo:nil];
137 + _downloadProgress = [[NSProgress alloc] initWithParent:nil userInfo:nil];
138 +
139 + __weak __typeof__(task) weakTask = task;
140 + for (NSProgress *progress in @[ _uploadProgress, _downloadProgress ])
141 + {
142 + progress.totalUnitCount = NSURLSessionTransferSizeUnknown;
143 + progress.cancellable = YES;
144 + progress.cancellationHandler = ^{
145 + [weakTask cancel];
146 + };
147 + progress.pausable = YES;
148 + progress.pausingHandler = ^{
149 + [weakTask suspend];
150 + };
151 + if ([progress respondsToSelector:@selector(setResumingHandler:)]) {
152 + progress.resumingHandler = ^{
153 + [weakTask resume];
154 + };
155 + }
156 + [progress addObserver:self
157 + forKeyPath:NSStringFromSelector(@selector(fractionCompleted))
158 + options:NSKeyValueObservingOptionNew
159 + context:NULL];
160 + }
161 + return self;
162 +}
163 +
164 +- (void)dealloc {
165 + [self.downloadProgress removeObserver:self forKeyPath:NSStringFromSelector(@selector(fractionCompleted))];
166 + [self.uploadProgress removeObserver:self forKeyPath:NSStringFromSelector(@selector(fractionCompleted))];
167 +}
168 +
169 +#pragma mark - NSProgress Tracking
170 +
171 +- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
172 + if ([object isEqual:self.downloadProgress]) {
173 + if (self.downloadProgressBlock) {
174 + self.downloadProgressBlock(object);
175 + }
176 + }
177 + else if ([object isEqual:self.uploadProgress]) {
178 + if (self.uploadProgressBlock) {
179 + self.uploadProgressBlock(object);
180 + }
181 + }
182 +}
183 +
184 +#pragma mark - NSURLSessionTaskDelegate
185 +
186 +- (void)URLSession:(__unused NSURLSession *)session
187 + task:(NSURLSessionTask *)task
188 +didCompleteWithError:(NSError *)error
189 +{
190 + __strong AFURLSessionManager *manager = self.manager;
191 +
192 + __block id responseObject = nil;
193 +
194 + __block NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
195 + userInfo[AFNetworkingTaskDidCompleteResponseSerializerKey] = manager.responseSerializer;
196 +
197 + //Performance Improvement from #2672
198 + NSData *data = nil;
199 + if (self.mutableData) {
200 + data = [self.mutableData copy];
201 + //We no longer need the reference, so nil it out to gain back some memory.
202 + self.mutableData = nil;
203 + }
204 +
205 + if (self.downloadFileURL) {
206 + userInfo[AFNetworkingTaskDidCompleteAssetPathKey] = self.downloadFileURL;
207 + } else if (data) {
208 + userInfo[AFNetworkingTaskDidCompleteResponseDataKey] = data;
209 + }
210 +
211 + if (error) {
212 + userInfo[AFNetworkingTaskDidCompleteErrorKey] = error;
213 +
214 + dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{
215 + if (self.completionHandler) {
216 + self.completionHandler(task.response, responseObject, error);
217 + }
218 +
219 + dispatch_async(dispatch_get_main_queue(), ^{
220 + [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo];
221 + });
222 + });
223 + } else {
224 + dispatch_async(url_session_manager_processing_queue(), ^{
225 + NSError *serializationError = nil;
226 + responseObject = [manager.responseSerializer responseObjectForResponse:task.response data:data error:&serializationError];
227 +
228 + if (self.downloadFileURL) {
229 + responseObject = self.downloadFileURL;
230 + }
231 +
232 + if (responseObject) {
233 + userInfo[AFNetworkingTaskDidCompleteSerializedResponseKey] = responseObject;
234 + }
235 +
236 + if (serializationError) {
237 + userInfo[AFNetworkingTaskDidCompleteErrorKey] = serializationError;
238 + }
239 +
240 + dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{
241 + if (self.completionHandler) {
242 + self.completionHandler(task.response, responseObject, serializationError);
243 + }
244 +
245 + dispatch_async(dispatch_get_main_queue(), ^{
246 + [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo];
247 + });
248 + });
249 + });
250 + }
251 +}
252 +
253 +#pragma mark - NSURLSessionDataDelegate
254 +
255 +- (void)URLSession:(__unused NSURLSession *)session
256 + dataTask:(__unused NSURLSessionDataTask *)dataTask
257 + didReceiveData:(NSData *)data
258 +{
259 + self.downloadProgress.totalUnitCount = dataTask.countOfBytesExpectedToReceive;
260 + self.downloadProgress.completedUnitCount = dataTask.countOfBytesReceived;
261 +
262 + [self.mutableData appendData:data];
263 +}
264 +
265 +- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
266 + didSendBodyData:(int64_t)bytesSent
267 + totalBytesSent:(int64_t)totalBytesSent
268 +totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend{
269 +
270 + self.uploadProgress.totalUnitCount = task.countOfBytesExpectedToSend;
271 + self.uploadProgress.completedUnitCount = task.countOfBytesSent;
272 +}
273 +
274 +#pragma mark - NSURLSessionDownloadDelegate
275 +
276 +- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
277 + didWriteData:(int64_t)bytesWritten
278 + totalBytesWritten:(int64_t)totalBytesWritten
279 +totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
280 +
281 + self.downloadProgress.totalUnitCount = totalBytesExpectedToWrite;
282 + self.downloadProgress.completedUnitCount = totalBytesWritten;
283 +}
284 +
285 +- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
286 + didResumeAtOffset:(int64_t)fileOffset
287 +expectedTotalBytes:(int64_t)expectedTotalBytes{
288 +
289 + self.downloadProgress.totalUnitCount = expectedTotalBytes;
290 + self.downloadProgress.completedUnitCount = fileOffset;
291 +}
292 +
293 +- (void)URLSession:(NSURLSession *)session
294 + downloadTask:(NSURLSessionDownloadTask *)downloadTask
295 +didFinishDownloadingToURL:(NSURL *)location
296 +{
297 + self.downloadFileURL = nil;
298 +
299 + if (self.downloadTaskDidFinishDownloading) {
300 + self.downloadFileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location);
301 + if (self.downloadFileURL) {
302 + NSError *fileManagerError = nil;
303 +
304 + if (![[NSFileManager defaultManager] moveItemAtURL:location toURL:self.downloadFileURL error:&fileManagerError]) {
305 + [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:fileManagerError.userInfo];
306 + }
307 + }
308 + }
309 +}
310 +
311 +@end
312 +
313 +#pragma mark -
314 +
315 +/**
316 + * A workaround for issues related to key-value observing the `state` of an `NSURLSessionTask`.
317 + *
318 + * See:
319 + * - https://github.com/AFNetworking/AFNetworking/issues/1477
320 + * - https://github.com/AFNetworking/AFNetworking/issues/2638
321 + * - https://github.com/AFNetworking/AFNetworking/pull/2702
322 + */
323 +
324 +static inline void af_swizzleSelector(Class theClass, SEL originalSelector, SEL swizzledSelector) {
325 + Method originalMethod = class_getInstanceMethod(theClass, originalSelector);
326 + Method swizzledMethod = class_getInstanceMethod(theClass, swizzledSelector);
327 + method_exchangeImplementations(originalMethod, swizzledMethod);
328 +}
329 +
330 +static inline BOOL af_addMethod(Class theClass, SEL selector, Method method) {
331 + return class_addMethod(theClass, selector, method_getImplementation(method), method_getTypeEncoding(method));
332 +}
333 +
334 +static NSString * const AFNSURLSessionTaskDidResumeNotification = @"com.alamofire.networking.nsurlsessiontask.resume";
335 +static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofire.networking.nsurlsessiontask.suspend";
336 +
337 +@interface _AFURLSessionTaskSwizzling : NSObject
338 +
339 +@end
340 +
341 +@implementation _AFURLSessionTaskSwizzling
342 +
343 ++ (void)load {
344 + /**
345 + WARNING: Trouble Ahead
346 + https://github.com/AFNetworking/AFNetworking/pull/2702
347 + */
348 +
349 + if (NSClassFromString(@"NSURLSessionTask")) {
350 + /**
351 + iOS 7 and iOS 8 differ in NSURLSessionTask implementation, which makes the next bit of code a bit tricky.
352 + Many Unit Tests have been built to validate as much of this behavior has possible.
353 + Here is what we know:
354 + - 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.
355 + - Simply referencing `[NSURLSessionTask class]` will not work. You need to ask an `NSURLSession` to actually create an object, and grab the class from there.
356 + - On iOS 7, `localDataTask` is a `__NSCFLocalDataTask`, which inherits from `__NSCFLocalSessionTask`, which inherits from `__NSCFURLSessionTask`.
357 + - On iOS 8, `localDataTask` is a `__NSCFLocalDataTask`, which inherits from `__NSCFLocalSessionTask`, which inherits from `NSURLSessionTask`.
358 + - 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.
359 + - 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.
360 + - 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.
361 +
362 + Some Assumptions:
363 + - 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.
364 + - No background task classes override `resume` or `suspend`
365 +
366 + The current solution:
367 + 1) Grab an instance of `__NSCFLocalDataTask` by asking an instance of `NSURLSession` for a data task.
368 + 2) Grab a pointer to the original implementation of `af_resume`
369 + 3) Check to see if the current class has an implementation of resume. If so, continue to step 4.
370 + 4) Grab the super class of the current class.
371 + 5) Grab a pointer for the current class to the current implementation of `resume`.
372 + 6) Grab a pointer for the super class to the current implementation of `resume`.
373 + 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
374 + 8) Set the current class to the super class, and repeat steps 3-8
375 + */
376 + NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
377 + NSURLSession * session = [NSURLSession sessionWithConfiguration:configuration];
378 +#pragma GCC diagnostic push
379 +#pragma GCC diagnostic ignored "-Wnonnull"
380 + NSURLSessionDataTask *localDataTask = [session dataTaskWithURL:nil];
381 +#pragma clang diagnostic pop
382 + IMP originalAFResumeIMP = method_getImplementation(class_getInstanceMethod([self class], @selector(af_resume)));
383 + Class currentClass = [localDataTask class];
384 +
385 + while (class_getInstanceMethod(currentClass, @selector(resume))) {
386 + Class superClass = [currentClass superclass];
387 + IMP classResumeIMP = method_getImplementation(class_getInstanceMethod(currentClass, @selector(resume)));
388 + IMP superclassResumeIMP = method_getImplementation(class_getInstanceMethod(superClass, @selector(resume)));
389 + if (classResumeIMP != superclassResumeIMP &&
390 + originalAFResumeIMP != classResumeIMP) {
391 + [self swizzleResumeAndSuspendMethodForClass:currentClass];
392 + }
393 + currentClass = [currentClass superclass];
394 + }
395 +
396 + [localDataTask cancel];
397 + [session finishTasksAndInvalidate];
398 + }
399 +}
400 +
401 ++ (void)swizzleResumeAndSuspendMethodForClass:(Class)theClass {
402 + Method afResumeMethod = class_getInstanceMethod(self, @selector(af_resume));
403 + Method afSuspendMethod = class_getInstanceMethod(self, @selector(af_suspend));
404 +
405 + if (af_addMethod(theClass, @selector(af_resume), afResumeMethod)) {
406 + af_swizzleSelector(theClass, @selector(resume), @selector(af_resume));
407 + }
408 +
409 + if (af_addMethod(theClass, @selector(af_suspend), afSuspendMethod)) {
410 + af_swizzleSelector(theClass, @selector(suspend), @selector(af_suspend));
411 + }
412 +}
413 +
414 +- (NSURLSessionTaskState)state {
415 + NSAssert(NO, @"State method should never be called in the actual dummy class");
416 + return NSURLSessionTaskStateCanceling;
417 +}
418 +
419 +- (void)af_resume {
420 + NSAssert([self respondsToSelector:@selector(state)], @"Does not respond to state");
421 + NSURLSessionTaskState state = [self state];
422 + [self af_resume];
423 +
424 + if (state != NSURLSessionTaskStateRunning) {
425 + [[NSNotificationCenter defaultCenter] postNotificationName:AFNSURLSessionTaskDidResumeNotification object:self];
426 + }
427 +}
428 +
429 +- (void)af_suspend {
430 + NSAssert([self respondsToSelector:@selector(state)], @"Does not respond to state");
431 + NSURLSessionTaskState state = [self state];
432 + [self af_suspend];
433 +
434 + if (state != NSURLSessionTaskStateSuspended) {
435 + [[NSNotificationCenter defaultCenter] postNotificationName:AFNSURLSessionTaskDidSuspendNotification object:self];
436 + }
437 +}
438 +@end
439 +
440 +#pragma mark -
441 +
442 +@interface AFURLSessionManager ()
443 +@property (readwrite, nonatomic, strong) NSURLSessionConfiguration *sessionConfiguration;
444 +@property (readwrite, nonatomic, strong) NSOperationQueue *operationQueue;
445 +@property (readwrite, nonatomic, strong) NSURLSession *session;
446 +@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableTaskDelegatesKeyedByTaskIdentifier;
447 +@property (readonly, nonatomic, copy) NSString *taskDescriptionForSessionTasks;
448 +@property (readwrite, nonatomic, strong) NSLock *lock;
449 +@property (readwrite, nonatomic, copy) AFURLSessionDidBecomeInvalidBlock sessionDidBecomeInvalid;
450 +@property (readwrite, nonatomic, copy) AFURLSessionDidReceiveAuthenticationChallengeBlock sessionDidReceiveAuthenticationChallenge;
451 +@property (readwrite, nonatomic, copy) AFURLSessionDidFinishEventsForBackgroundURLSessionBlock didFinishEventsForBackgroundURLSession;
452 +@property (readwrite, nonatomic, copy) AFURLSessionTaskWillPerformHTTPRedirectionBlock taskWillPerformHTTPRedirection;
453 +@property (readwrite, nonatomic, copy) AFURLSessionTaskDidReceiveAuthenticationChallengeBlock taskDidReceiveAuthenticationChallenge;
454 +@property (readwrite, nonatomic, copy) AFURLSessionTaskNeedNewBodyStreamBlock taskNeedNewBodyStream;
455 +@property (readwrite, nonatomic, copy) AFURLSessionTaskDidSendBodyDataBlock taskDidSendBodyData;
456 +@property (readwrite, nonatomic, copy) AFURLSessionTaskDidCompleteBlock taskDidComplete;
457 +@property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidReceiveResponseBlock dataTaskDidReceiveResponse;
458 +@property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidBecomeDownloadTaskBlock dataTaskDidBecomeDownloadTask;
459 +@property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidReceiveDataBlock dataTaskDidReceiveData;
460 +@property (readwrite, nonatomic, copy) AFURLSessionDataTaskWillCacheResponseBlock dataTaskWillCacheResponse;
461 +@property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidFinishDownloadingBlock downloadTaskDidFinishDownloading;
462 +@property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidWriteDataBlock downloadTaskDidWriteData;
463 +@property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidResumeBlock downloadTaskDidResume;
464 +@end
465 +
466 +@implementation AFURLSessionManager
467 +
468 +- (instancetype)init {
469 + return [self initWithSessionConfiguration:nil];
470 +}
471 +
472 +- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration {
473 + self = [super init];
474 + if (!self) {
475 + return nil;
476 + }
477 +
478 + if (!configuration) {
479 + configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
480 + }
481 +
482 + self.sessionConfiguration = configuration;
483 +
484 + self.operationQueue = [[NSOperationQueue alloc] init];
485 + self.operationQueue.maxConcurrentOperationCount = 1;
486 +
487 + self.session = [NSURLSession sessionWithConfiguration:self.sessionConfiguration delegate:self delegateQueue:self.operationQueue];
488 +
489 + self.responseSerializer = [AFJSONResponseSerializer serializer];
490 +
491 + self.securityPolicy = [AFSecurityPolicy defaultPolicy];
492 +
493 +#if !TARGET_OS_WATCH
494 + self.reachabilityManager = [AFNetworkReachabilityManager sharedManager];
495 +#endif
496 +
497 + self.mutableTaskDelegatesKeyedByTaskIdentifier = [[NSMutableDictionary alloc] init];
498 +
499 + self.lock = [[NSLock alloc] init];
500 + self.lock.name = AFURLSessionManagerLockName;
501 +
502 + [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
503 + for (NSURLSessionDataTask *task in dataTasks) {
504 + [self addDelegateForDataTask:task uploadProgress:nil downloadProgress:nil completionHandler:nil];
505 + }
506 +
507 + for (NSURLSessionUploadTask *uploadTask in uploadTasks) {
508 + [self addDelegateForUploadTask:uploadTask progress:nil completionHandler:nil];
509 + }
510 +
511 + for (NSURLSessionDownloadTask *downloadTask in downloadTasks) {
512 + [self addDelegateForDownloadTask:downloadTask progress:nil destination:nil completionHandler:nil];
513 + }
514 + }];
515 +
516 + return self;
517 +}
518 +
519 +- (void)dealloc {
520 + [[NSNotificationCenter defaultCenter] removeObserver:self];
521 +}
522 +
523 +#pragma mark -
524 +
525 +- (NSString *)taskDescriptionForSessionTasks {
526 + return [NSString stringWithFormat:@"%p", self];
527 +}
528 +
529 +- (void)taskDidResume:(NSNotification *)notification {
530 + NSURLSessionTask *task = notification.object;
531 + if ([task respondsToSelector:@selector(taskDescription)]) {
532 + if ([task.taskDescription isEqualToString:self.taskDescriptionForSessionTasks]) {
533 + dispatch_async(dispatch_get_main_queue(), ^{
534 + [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidResumeNotification object:task];
535 + });
536 + }
537 + }
538 +}
539 +
540 +- (void)taskDidSuspend:(NSNotification *)notification {
541 + NSURLSessionTask *task = notification.object;
542 + if ([task respondsToSelector:@selector(taskDescription)]) {
543 + if ([task.taskDescription isEqualToString:self.taskDescriptionForSessionTasks]) {
544 + dispatch_async(dispatch_get_main_queue(), ^{
545 + [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidSuspendNotification object:task];
546 + });
547 + }
548 + }
549 +}
550 +
551 +#pragma mark -
552 +
553 +- (AFURLSessionManagerTaskDelegate *)delegateForTask:(NSURLSessionTask *)task {
554 + NSParameterAssert(task);
555 +
556 + AFURLSessionManagerTaskDelegate *delegate = nil;
557 + [self.lock lock];
558 + delegate = self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)];
559 + [self.lock unlock];
560 +
561 + return delegate;
562 +}
563 +
564 +- (void)setDelegate:(AFURLSessionManagerTaskDelegate *)delegate
565 + forTask:(NSURLSessionTask *)task
566 +{
567 + NSParameterAssert(task);
568 + NSParameterAssert(delegate);
569 +
570 + [self.lock lock];
571 + self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)] = delegate;
572 + [self addNotificationObserverForTask:task];
573 + [self.lock unlock];
574 +}
575 +
576 +- (void)addDelegateForDataTask:(NSURLSessionDataTask *)dataTask
577 + uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock
578 + downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock
579 + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
580 +{
581 + AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] initWithTask:dataTask];
582 + delegate.manager = self;
583 + delegate.completionHandler = completionHandler;
584 +
585 + dataTask.taskDescription = self.taskDescriptionForSessionTasks;
586 + [self setDelegate:delegate forTask:dataTask];
587 +
588 + delegate.uploadProgressBlock = uploadProgressBlock;
589 + delegate.downloadProgressBlock = downloadProgressBlock;
590 +}
591 +
592 +- (void)addDelegateForUploadTask:(NSURLSessionUploadTask *)uploadTask
593 + progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock
594 + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
595 +{
596 + AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] initWithTask:uploadTask];
597 + delegate.manager = self;
598 + delegate.completionHandler = completionHandler;
599 +
600 + uploadTask.taskDescription = self.taskDescriptionForSessionTasks;
601 +
602 + [self setDelegate:delegate forTask:uploadTask];
603 +
604 + delegate.uploadProgressBlock = uploadProgressBlock;
605 +}
606 +
607 +- (void)addDelegateForDownloadTask:(NSURLSessionDownloadTask *)downloadTask
608 + progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock
609 + destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
610 + completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler
611 +{
612 + AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] initWithTask:downloadTask];
613 + delegate.manager = self;
614 + delegate.completionHandler = completionHandler;
615 +
616 + if (destination) {
617 + delegate.downloadTaskDidFinishDownloading = ^NSURL * (NSURLSession * __unused session, NSURLSessionDownloadTask *task, NSURL *location) {
618 + return destination(location, task.response);
619 + };
620 + }
621 +
622 + downloadTask.taskDescription = self.taskDescriptionForSessionTasks;
623 +
624 + [self setDelegate:delegate forTask:downloadTask];
625 +
626 + delegate.downloadProgressBlock = downloadProgressBlock;
627 +}
628 +
629 +- (void)removeDelegateForTask:(NSURLSessionTask *)task {
630 + NSParameterAssert(task);
631 +
632 + [self.lock lock];
633 + [self removeNotificationObserverForTask:task];
634 + [self.mutableTaskDelegatesKeyedByTaskIdentifier removeObjectForKey:@(task.taskIdentifier)];
635 + [self.lock unlock];
636 +}
637 +
638 +#pragma mark -
639 +
640 +- (NSArray *)tasksForKeyPath:(NSString *)keyPath {
641 + __block NSArray *tasks = nil;
642 + dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
643 + [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
644 + if ([keyPath isEqualToString:NSStringFromSelector(@selector(dataTasks))]) {
645 + tasks = dataTasks;
646 + } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(uploadTasks))]) {
647 + tasks = uploadTasks;
648 + } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(downloadTasks))]) {
649 + tasks = downloadTasks;
650 + } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(tasks))]) {
651 + tasks = [@[dataTasks, uploadTasks, downloadTasks] valueForKeyPath:@"@unionOfArrays.self"];
652 + }
653 +
654 + dispatch_semaphore_signal(semaphore);
655 + }];
656 +
657 + dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
658 +
659 + return tasks;
660 +}
661 +
662 +- (NSArray *)tasks {
663 + return [self tasksForKeyPath:NSStringFromSelector(_cmd)];
664 +}
665 +
666 +- (NSArray *)dataTasks {
667 + return [self tasksForKeyPath:NSStringFromSelector(_cmd)];
668 +}
669 +
670 +- (NSArray *)uploadTasks {
671 + return [self tasksForKeyPath:NSStringFromSelector(_cmd)];
672 +}
673 +
674 +- (NSArray *)downloadTasks {
675 + return [self tasksForKeyPath:NSStringFromSelector(_cmd)];
676 +}
677 +
678 +#pragma mark -
679 +
680 +- (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks {
681 + if (cancelPendingTasks) {
682 + [self.session invalidateAndCancel];
683 + } else {
684 + [self.session finishTasksAndInvalidate];
685 + }
686 +}
687 +
688 +#pragma mark -
689 +
690 +- (void)setResponseSerializer:(id <AFURLResponseSerialization>)responseSerializer {
691 + NSParameterAssert(responseSerializer);
692 +
693 + _responseSerializer = responseSerializer;
694 +}
695 +
696 +#pragma mark -
697 +- (void)addNotificationObserverForTask:(NSURLSessionTask *)task {
698 + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidResume:) name:AFNSURLSessionTaskDidResumeNotification object:task];
699 + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidSuspend:) name:AFNSURLSessionTaskDidSuspendNotification object:task];
700 +}
701 +
702 +- (void)removeNotificationObserverForTask:(NSURLSessionTask *)task {
703 + [[NSNotificationCenter defaultCenter] removeObserver:self name:AFNSURLSessionTaskDidSuspendNotification object:task];
704 + [[NSNotificationCenter defaultCenter] removeObserver:self name:AFNSURLSessionTaskDidResumeNotification object:task];
705 +}
706 +
707 +#pragma mark -
708 +
709 +- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
710 + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
711 +{
712 + return [self dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:completionHandler];
713 +}
714 +
715 +- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
716 + uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock
717 + downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock
718 + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler {
719 +
720 + __block NSURLSessionDataTask *dataTask = nil;
721 + url_session_manager_create_task_safely(^{
722 + dataTask = [self.session dataTaskWithRequest:request];
723 + });
724 +
725 + [self addDelegateForDataTask:dataTask uploadProgress:uploadProgressBlock downloadProgress:downloadProgressBlock completionHandler:completionHandler];
726 +
727 + return dataTask;
728 +}
729 +
730 +#pragma mark -
731 +
732 +- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
733 + fromFile:(NSURL *)fileURL
734 + progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock
735 + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
736 +{
737 + __block NSURLSessionUploadTask *uploadTask = nil;
738 + url_session_manager_create_task_safely(^{
739 + uploadTask = [self.session uploadTaskWithRequest:request fromFile:fileURL];
740 + });
741 +
742 + // uploadTask may be nil on iOS7 because uploadTaskWithRequest:fromFile: may return nil despite being documented as nonnull (https://devforums.apple.com/message/926113#926113)
743 + if (!uploadTask && self.attemptsToRecreateUploadTasksForBackgroundSessions && self.session.configuration.identifier) {
744 + for (NSUInteger attempts = 0; !uploadTask && attempts < AFMaximumNumberOfAttemptsToRecreateBackgroundSessionUploadTask; attempts++) {
745 + uploadTask = [self.session uploadTaskWithRequest:request fromFile:fileURL];
746 + }
747 + }
748 +
749 + [self addDelegateForUploadTask:uploadTask progress:uploadProgressBlock completionHandler:completionHandler];
750 +
751 + return uploadTask;
752 +}
753 +
754 +- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
755 + fromData:(NSData *)bodyData
756 + progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock
757 + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
758 +{
759 + __block NSURLSessionUploadTask *uploadTask = nil;
760 + url_session_manager_create_task_safely(^{
761 + uploadTask = [self.session uploadTaskWithRequest:request fromData:bodyData];
762 + });
763 +
764 + [self addDelegateForUploadTask:uploadTask progress:uploadProgressBlock completionHandler:completionHandler];
765 +
766 + return uploadTask;
767 +}
768 +
769 +- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request
770 + progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock
771 + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
772 +{
773 + __block NSURLSessionUploadTask *uploadTask = nil;
774 + url_session_manager_create_task_safely(^{
775 + uploadTask = [self.session uploadTaskWithStreamedRequest:request];
776 + });
777 +
778 + [self addDelegateForUploadTask:uploadTask progress:uploadProgressBlock completionHandler:completionHandler];
779 +
780 + return uploadTask;
781 +}
782 +
783 +#pragma mark -
784 +
785 +- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request
786 + progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock
787 + destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
788 + completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler
789 +{
790 + __block NSURLSessionDownloadTask *downloadTask = nil;
791 + url_session_manager_create_task_safely(^{
792 + downloadTask = [self.session downloadTaskWithRequest:request];
793 + });
794 +
795 + [self addDelegateForDownloadTask:downloadTask progress:downloadProgressBlock destination:destination completionHandler:completionHandler];
796 +
797 + return downloadTask;
798 +}
799 +
800 +- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData
801 + progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock
802 + destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
803 + completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler
804 +{
805 + __block NSURLSessionDownloadTask *downloadTask = nil;
806 + url_session_manager_create_task_safely(^{
807 + downloadTask = [self.session downloadTaskWithResumeData:resumeData];
808 + });
809 +
810 + [self addDelegateForDownloadTask:downloadTask progress:downloadProgressBlock destination:destination completionHandler:completionHandler];
811 +
812 + return downloadTask;
813 +}
814 +
815 +#pragma mark -
816 +- (NSProgress *)uploadProgressForTask:(NSURLSessionTask *)task {
817 + return [[self delegateForTask:task] uploadProgress];
818 +}
819 +
820 +- (NSProgress *)downloadProgressForTask:(NSURLSessionTask *)task {
821 + return [[self delegateForTask:task] downloadProgress];
822 +}
823 +
824 +#pragma mark -
825 +
826 +- (void)setSessionDidBecomeInvalidBlock:(void (^)(NSURLSession *session, NSError *error))block {
827 + self.sessionDidBecomeInvalid = block;
828 +}
829 +
830 +- (void)setSessionDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block {
831 + self.sessionDidReceiveAuthenticationChallenge = block;
832 +}
833 +
834 +- (void)setDidFinishEventsForBackgroundURLSessionBlock:(void (^)(NSURLSession *session))block {
835 + self.didFinishEventsForBackgroundURLSession = block;
836 +}
837 +
838 +#pragma mark -
839 +
840 +- (void)setTaskNeedNewBodyStreamBlock:(NSInputStream * (^)(NSURLSession *session, NSURLSessionTask *task))block {
841 + self.taskNeedNewBodyStream = block;
842 +}
843 +
844 +- (void)setTaskWillPerformHTTPRedirectionBlock:(NSURLRequest * (^)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request))block {
845 + self.taskWillPerformHTTPRedirection = block;
846 +}
847 +
848 +- (void)setTaskDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block {
849 + self.taskDidReceiveAuthenticationChallenge = block;
850 +}
851 +
852 +- (void)setTaskDidSendBodyDataBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))block {
853 + self.taskDidSendBodyData = block;
854 +}
855 +
856 +- (void)setTaskDidCompleteBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, NSError *error))block {
857 + self.taskDidComplete = block;
858 +}
859 +
860 +#pragma mark -
861 +
862 +- (void)setDataTaskDidReceiveResponseBlock:(NSURLSessionResponseDisposition (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response))block {
863 + self.dataTaskDidReceiveResponse = block;
864 +}
865 +
866 +- (void)setDataTaskDidBecomeDownloadTaskBlock:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask))block {
867 + self.dataTaskDidBecomeDownloadTask = block;
868 +}
869 +
870 +- (void)setDataTaskDidReceiveDataBlock:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data))block {
871 + self.dataTaskDidReceiveData = block;
872 +}
873 +
874 +- (void)setDataTaskWillCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse))block {
875 + self.dataTaskWillCacheResponse = block;
876 +}
877 +
878 +#pragma mark -
879 +
880 +- (void)setDownloadTaskDidFinishDownloadingBlock:(NSURL * (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block {
881 + self.downloadTaskDidFinishDownloading = block;
882 +}
883 +
884 +- (void)setDownloadTaskDidWriteDataBlock:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite))block {
885 + self.downloadTaskDidWriteData = block;
886 +}
887 +
888 +- (void)setDownloadTaskDidResumeBlock:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes))block {
889 + self.downloadTaskDidResume = block;
890 +}
891 +
892 +#pragma mark - NSObject
893 +
894 +- (NSString *)description {
895 + return [NSString stringWithFormat:@"<%@: %p, session: %@, operationQueue: %@>", NSStringFromClass([self class]), self, self.session, self.operationQueue];
896 +}
897 +
898 +- (BOOL)respondsToSelector:(SEL)selector {
899 + if (selector == @selector(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:)) {
900 + return self.taskWillPerformHTTPRedirection != nil;
901 + } else if (selector == @selector(URLSession:dataTask:didReceiveResponse:completionHandler:)) {
902 + return self.dataTaskDidReceiveResponse != nil;
903 + } else if (selector == @selector(URLSession:dataTask:willCacheResponse:completionHandler:)) {
904 + return self.dataTaskWillCacheResponse != nil;
905 + } else if (selector == @selector(URLSessionDidFinishEventsForBackgroundURLSession:)) {
906 + return self.didFinishEventsForBackgroundURLSession != nil;
907 + }
908 +
909 + return [[self class] instancesRespondToSelector:selector];
910 +}
911 +
912 +#pragma mark - NSURLSessionDelegate
913 +
914 +- (void)URLSession:(NSURLSession *)session
915 +didBecomeInvalidWithError:(NSError *)error
916 +{
917 + if (self.sessionDidBecomeInvalid) {
918 + self.sessionDidBecomeInvalid(session, error);
919 + }
920 +
921 + [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDidInvalidateNotification object:session];
922 +}
923 +
924 +- (void)URLSession:(NSURLSession *)session
925 +didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
926 + completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
927 +{
928 + NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
929 + __block NSURLCredential *credential = nil;
930 +
931 + if (self.sessionDidReceiveAuthenticationChallenge) {
932 + disposition = self.sessionDidReceiveAuthenticationChallenge(session, challenge, &credential);
933 + } else {
934 + if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
935 + if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) {
936 + credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
937 + if (credential) {
938 + disposition = NSURLSessionAuthChallengeUseCredential;
939 + } else {
940 + disposition = NSURLSessionAuthChallengePerformDefaultHandling;
941 + }
942 + } else {
943 + disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
944 + }
945 + } else {
946 + disposition = NSURLSessionAuthChallengePerformDefaultHandling;
947 + }
948 + }
949 +
950 + if (completionHandler) {
951 + completionHandler(disposition, credential);
952 + }
953 +}
954 +
955 +#pragma mark - NSURLSessionTaskDelegate
956 +
957 +- (void)URLSession:(NSURLSession *)session
958 + task:(NSURLSessionTask *)task
959 +willPerformHTTPRedirection:(NSHTTPURLResponse *)response
960 + newRequest:(NSURLRequest *)request
961 + completionHandler:(void (^)(NSURLRequest *))completionHandler
962 +{
963 + NSURLRequest *redirectRequest = request;
964 +
965 + if (self.taskWillPerformHTTPRedirection) {
966 + redirectRequest = self.taskWillPerformHTTPRedirection(session, task, response, request);
967 + }
968 +
969 + if (completionHandler) {
970 + completionHandler(redirectRequest);
971 + }
972 +}
973 +
974 +- (void)URLSession:(NSURLSession *)session
975 + task:(NSURLSessionTask *)task
976 +didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
977 + completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
978 +{
979 + NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
980 + __block NSURLCredential *credential = nil;
981 +
982 + if (self.taskDidReceiveAuthenticationChallenge) {
983 + disposition = self.taskDidReceiveAuthenticationChallenge(session, task, challenge, &credential);
984 + } else {
985 + if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
986 + if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) {
987 + disposition = NSURLSessionAuthChallengeUseCredential;
988 + credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
989 + } else {
990 + disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
991 + }
992 + } else {
993 + disposition = NSURLSessionAuthChallengePerformDefaultHandling;
994 + }
995 + }
996 +
997 + if (completionHandler) {
998 + completionHandler(disposition, credential);
999 + }
1000 +}
1001 +
1002 +- (void)URLSession:(NSURLSession *)session
1003 + task:(NSURLSessionTask *)task
1004 + needNewBodyStream:(void (^)(NSInputStream *bodyStream))completionHandler
1005 +{
1006 + NSInputStream *inputStream = nil;
1007 +
1008 + if (self.taskNeedNewBodyStream) {
1009 + inputStream = self.taskNeedNewBodyStream(session, task);
1010 + } else if (task.originalRequest.HTTPBodyStream && [task.originalRequest.HTTPBodyStream conformsToProtocol:@protocol(NSCopying)]) {
1011 + inputStream = [task.originalRequest.HTTPBodyStream copy];
1012 + }
1013 +
1014 + if (completionHandler) {
1015 + completionHandler(inputStream);
1016 + }
1017 +}
1018 +
1019 +- (void)URLSession:(NSURLSession *)session
1020 + task:(NSURLSessionTask *)task
1021 + didSendBodyData:(int64_t)bytesSent
1022 + totalBytesSent:(int64_t)totalBytesSent
1023 +totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
1024 +{
1025 +
1026 + int64_t totalUnitCount = totalBytesExpectedToSend;
1027 + if(totalUnitCount == NSURLSessionTransferSizeUnknown) {
1028 + NSString *contentLength = [task.originalRequest valueForHTTPHeaderField:@"Content-Length"];
1029 + if(contentLength) {
1030 + totalUnitCount = (int64_t) [contentLength longLongValue];
1031 + }
1032 + }
1033 +
1034 + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task];
1035 +
1036 + if (delegate) {
1037 + [delegate URLSession:session task:task didSendBodyData:bytesSent totalBytesSent:totalBytesSent totalBytesExpectedToSend:totalBytesExpectedToSend];
1038 + }
1039 +
1040 + if (self.taskDidSendBodyData) {
1041 + self.taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalUnitCount);
1042 + }
1043 +}
1044 +
1045 +- (void)URLSession:(NSURLSession *)session
1046 + task:(NSURLSessionTask *)task
1047 +didCompleteWithError:(NSError *)error
1048 +{
1049 + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task];
1050 +
1051 + // delegate may be nil when completing a task in the background
1052 + if (delegate) {
1053 + [delegate URLSession:session task:task didCompleteWithError:error];
1054 +
1055 + [self removeDelegateForTask:task];
1056 + }
1057 +
1058 + if (self.taskDidComplete) {
1059 + self.taskDidComplete(session, task, error);
1060 + }
1061 +}
1062 +
1063 +#pragma mark - NSURLSessionDataDelegate
1064 +
1065 +- (void)URLSession:(NSURLSession *)session
1066 + dataTask:(NSURLSessionDataTask *)dataTask
1067 +didReceiveResponse:(NSURLResponse *)response
1068 + completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler
1069 +{
1070 + NSURLSessionResponseDisposition disposition = NSURLSessionResponseAllow;
1071 +
1072 + if (self.dataTaskDidReceiveResponse) {
1073 + disposition = self.dataTaskDidReceiveResponse(session, dataTask, response);
1074 + }
1075 +
1076 + if (completionHandler) {
1077 + completionHandler(disposition);
1078 + }
1079 +}
1080 +
1081 +- (void)URLSession:(NSURLSession *)session
1082 + dataTask:(NSURLSessionDataTask *)dataTask
1083 +didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask
1084 +{
1085 + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:dataTask];
1086 + if (delegate) {
1087 + [self removeDelegateForTask:dataTask];
1088 + [self setDelegate:delegate forTask:downloadTask];
1089 + }
1090 +
1091 + if (self.dataTaskDidBecomeDownloadTask) {
1092 + self.dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask);
1093 + }
1094 +}
1095 +
1096 +- (void)URLSession:(NSURLSession *)session
1097 + dataTask:(NSURLSessionDataTask *)dataTask
1098 + didReceiveData:(NSData *)data
1099 +{
1100 +
1101 + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:dataTask];
1102 + [delegate URLSession:session dataTask:dataTask didReceiveData:data];
1103 +
1104 + if (self.dataTaskDidReceiveData) {
1105 + self.dataTaskDidReceiveData(session, dataTask, data);
1106 + }
1107 +}
1108 +
1109 +- (void)URLSession:(NSURLSession *)session
1110 + dataTask:(NSURLSessionDataTask *)dataTask
1111 + willCacheResponse:(NSCachedURLResponse *)proposedResponse
1112 + completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler
1113 +{
1114 + NSCachedURLResponse *cachedResponse = proposedResponse;
1115 +
1116 + if (self.dataTaskWillCacheResponse) {
1117 + cachedResponse = self.dataTaskWillCacheResponse(session, dataTask, proposedResponse);
1118 + }
1119 +
1120 + if (completionHandler) {
1121 + completionHandler(cachedResponse);
1122 + }
1123 +}
1124 +
1125 +- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session {
1126 + if (self.didFinishEventsForBackgroundURLSession) {
1127 + dispatch_async(dispatch_get_main_queue(), ^{
1128 + self.didFinishEventsForBackgroundURLSession(session);
1129 + });
1130 + }
1131 +}
1132 +
1133 +#pragma mark - NSURLSessionDownloadDelegate
1134 +
1135 +- (void)URLSession:(NSURLSession *)session
1136 + downloadTask:(NSURLSessionDownloadTask *)downloadTask
1137 +didFinishDownloadingToURL:(NSURL *)location
1138 +{
1139 + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask];
1140 + if (self.downloadTaskDidFinishDownloading) {
1141 + NSURL *fileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location);
1142 + if (fileURL) {
1143 + delegate.downloadFileURL = fileURL;
1144 + NSError *error = nil;
1145 +
1146 + if (![[NSFileManager defaultManager] moveItemAtURL:location toURL:fileURL error:&error]) {
1147 + [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:error.userInfo];
1148 + }
1149 +
1150 + return;
1151 + }
1152 + }
1153 +
1154 + if (delegate) {
1155 + [delegate URLSession:session downloadTask:downloadTask didFinishDownloadingToURL:location];
1156 + }
1157 +}
1158 +
1159 +- (void)URLSession:(NSURLSession *)session
1160 + downloadTask:(NSURLSessionDownloadTask *)downloadTask
1161 + didWriteData:(int64_t)bytesWritten
1162 + totalBytesWritten:(int64_t)totalBytesWritten
1163 +totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
1164 +{
1165 +
1166 + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask];
1167 +
1168 + if (delegate) {
1169 + [delegate URLSession:session downloadTask:downloadTask didWriteData:bytesWritten totalBytesWritten:totalBytesWritten totalBytesExpectedToWrite:totalBytesExpectedToWrite];
1170 + }
1171 +
1172 + if (self.downloadTaskDidWriteData) {
1173 + self.downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
1174 + }
1175 +}
1176 +
1177 +- (void)URLSession:(NSURLSession *)session
1178 + downloadTask:(NSURLSessionDownloadTask *)downloadTask
1179 + didResumeAtOffset:(int64_t)fileOffset
1180 +expectedTotalBytes:(int64_t)expectedTotalBytes
1181 +{
1182 +
1183 + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask];
1184 +
1185 + if (delegate) {
1186 + [delegate URLSession:session downloadTask:downloadTask didResumeAtOffset:fileOffset expectedTotalBytes:expectedTotalBytes];
1187 + }
1188 +
1189 + if (self.downloadTaskDidResume) {
1190 + self.downloadTaskDidResume(session, downloadTask, fileOffset, expectedTotalBytes);
1191 + }
1192 +}
1193 +
1194 +#pragma mark - NSSecureCoding
1195 +
1196 ++ (BOOL)supportsSecureCoding {
1197 + return YES;
1198 +}
1199 +
1200 +- (instancetype)initWithCoder:(NSCoder *)decoder {
1201 + NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"];
1202 +
1203 + self = [self initWithSessionConfiguration:configuration];
1204 + if (!self) {
1205 + return nil;
1206 + }
1207 +
1208 + return self;
1209 +}
1210 +
1211 +- (void)encodeWithCoder:(NSCoder *)coder {
1212 + [coder encodeObject:self.session.configuration forKey:@"sessionConfiguration"];
1213 +}
1214 +
1215 +#pragma mark - NSCopying
1216 +
1217 +- (instancetype)copyWithZone:(NSZone *)zone {
1218 + return [[[self class] allocWithZone:zone] initWithSessionConfiguration:self.session.configuration];
1219 +}
1220 +
1221 +@end
1 +// AFAutoPurgingImageCache.h
2 +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 +//
4 +// Permission is hereby granted, free of charge, to any person obtaining a copy
5 +// of this software and associated documentation files (the "Software"), to deal
6 +// in the Software without restriction, including without limitation the rights
7 +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 +// copies of the Software, and to permit persons to whom the Software is
9 +// furnished to do so, subject to the following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included in
12 +// all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 +// THE SOFTWARE.
21 +
22 +#import <TargetConditionals.h>
23 +#import <Foundation/Foundation.h>
24 +
25 +#if TARGET_OS_IOS || TARGET_OS_TV
26 +#import <UIKit/UIKit.h>
27 +
28 +NS_ASSUME_NONNULL_BEGIN
29 +
30 +/**
31 + The `AFImageCache` protocol defines a set of APIs for adding, removing and fetching images from a cache synchronously.
32 + */
33 +@protocol AFImageCache <NSObject>
34 +
35 +/**
36 + Adds the image to the cache with the given identifier.
37 +
38 + @param image The image to cache.
39 + @param identifier The unique identifier for the image in the cache.
40 + */
41 +- (void)addImage:(UIImage *)image withIdentifier:(NSString *)identifier;
42 +
43 +/**
44 + Removes the image from the cache matching the given identifier.
45 +
46 + @param identifier The unique identifier for the image in the cache.
47 +
48 + @return A BOOL indicating whether or not the image was removed from the cache.
49 + */
50 +- (BOOL)removeImageWithIdentifier:(NSString *)identifier;
51 +
52 +/**
53 + Removes all images from the cache.
54 +
55 + @return A BOOL indicating whether or not all images were removed from the cache.
56 + */
57 +- (BOOL)removeAllImages;
58 +
59 +/**
60 + Returns the image in the cache associated with the given identifier.
61 +
62 + @param identifier The unique identifier for the image in the cache.
63 +
64 + @return An image for the matching identifier, or nil.
65 + */
66 +- (nullable UIImage *)imageWithIdentifier:(NSString *)identifier;
67 +@end
68 +
69 +
70 +/**
71 + 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.
72 + */
73 +@protocol AFImageRequestCache <AFImageCache>
74 +
75 +/**
76 + Adds the image to the cache using an identifier created from the request and additional identifier.
77 +
78 + @param image The image to cache.
79 + @param request The unique URL request identifing the image asset.
80 + @param identifier The additional identifier to apply to the URL request to identify the image.
81 + */
82 +- (void)addImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier;
83 +
84 +/**
85 + Removes the image from the cache using an identifier created from the request and additional identifier.
86 +
87 + @param request The unique URL request identifing the image asset.
88 + @param identifier The additional identifier to apply to the URL request to identify the image.
89 +
90 + @return A BOOL indicating whether or not all images were removed from the cache.
91 + */
92 +- (BOOL)removeImageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier;
93 +
94 +/**
95 + Returns the image from the cache associated with an identifier created from the request and additional identifier.
96 +
97 + @param request The unique URL request identifing the image asset.
98 + @param identifier The additional identifier to apply to the URL request to identify the image.
99 +
100 + @return An image for the matching request and identifier, or nil.
101 + */
102 +- (nullable UIImage *)imageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier;
103 +
104 +@end
105 +
106 +/**
107 + 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.
108 + */
109 +@interface AFAutoPurgingImageCache : NSObject <AFImageRequestCache>
110 +
111 +/**
112 + The total memory capacity of the cache in bytes.
113 + */
114 +@property (nonatomic, assign) UInt64 memoryCapacity;
115 +
116 +/**
117 + The preferred memory usage after purge in bytes. During a purge, images will be purged until the memory capacity drops below this limit.
118 + */
119 +@property (nonatomic, assign) UInt64 preferredMemoryUsageAfterPurge;
120 +
121 +/**
122 + The current total memory usage in bytes of all images stored within the cache.
123 + */
124 +@property (nonatomic, assign, readonly) UInt64 memoryUsage;
125 +
126 +/**
127 + 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`.
128 +
129 + @return The new `AutoPurgingImageCache` instance.
130 + */
131 +- (instancetype)init;
132 +
133 +/**
134 + Initialies the `AutoPurgingImageCache` instance with the given memory capacity and preferred memory usage
135 + after purge limit.
136 +
137 + @param memoryCapacity The total memory capacity of the cache in bytes.
138 + @param preferredMemoryCapacity The preferred memory usage after purge in bytes.
139 +
140 + @return The new `AutoPurgingImageCache` instance.
141 + */
142 +- (instancetype)initWithMemoryCapacity:(UInt64)memoryCapacity preferredMemoryCapacity:(UInt64)preferredMemoryCapacity;
143 +
144 +@end
145 +
146 +NS_ASSUME_NONNULL_END
147 +
148 +#endif
149 +
1 +// AFAutoPurgingImageCache.m
2 +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 +//
4 +// Permission is hereby granted, free of charge, to any person obtaining a copy
5 +// of this software and associated documentation files (the "Software"), to deal
6 +// in the Software without restriction, including without limitation the rights
7 +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 +// copies of the Software, and to permit persons to whom the Software is
9 +// furnished to do so, subject to the following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included in
12 +// all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 +// THE SOFTWARE.
21 +
22 +#import <TargetConditionals.h>
23 +
24 +#if TARGET_OS_IOS || TARGET_OS_TV
25 +
26 +#import "AFAutoPurgingImageCache.h"
27 +
28 +@interface AFCachedImage : NSObject
29 +
30 +@property (nonatomic, strong) UIImage *image;
31 +@property (nonatomic, strong) NSString *identifier;
32 +@property (nonatomic, assign) UInt64 totalBytes;
33 +@property (nonatomic, strong) NSDate *lastAccessDate;
34 +@property (nonatomic, assign) UInt64 currentMemoryUsage;
35 +
36 +@end
37 +
38 +@implementation AFCachedImage
39 +
40 +-(instancetype)initWithImage:(UIImage *)image identifier:(NSString *)identifier {
41 + if (self = [self init]) {
42 + self.image = image;
43 + self.identifier = identifier;
44 +
45 + CGSize imageSize = CGSizeMake(image.size.width * image.scale, image.size.height * image.scale);
46 + CGFloat bytesPerPixel = 4.0;
47 + CGFloat bytesPerSize = imageSize.width * imageSize.height;
48 + self.totalBytes = (UInt64)bytesPerPixel * (UInt64)bytesPerSize;
49 + self.lastAccessDate = [NSDate date];
50 + }
51 + return self;
52 +}
53 +
54 +- (UIImage*)accessImage {
55 + self.lastAccessDate = [NSDate date];
56 + return self.image;
57 +}
58 +
59 +- (NSString *)description {
60 + NSString *descriptionString = [NSString stringWithFormat:@"Idenfitier: %@ lastAccessDate: %@ ", self.identifier, self.lastAccessDate];
61 + return descriptionString;
62 +
63 +}
64 +
65 +@end
66 +
67 +@interface AFAutoPurgingImageCache ()
68 +@property (nonatomic, strong) NSMutableDictionary <NSString* , AFCachedImage*> *cachedImages;
69 +@property (nonatomic, assign) UInt64 currentMemoryUsage;
70 +@property (nonatomic, strong) dispatch_queue_t synchronizationQueue;
71 +@end
72 +
73 +@implementation AFAutoPurgingImageCache
74 +
75 +- (instancetype)init {
76 + return [self initWithMemoryCapacity:100 * 1024 * 1024 preferredMemoryCapacity:60 * 1024 * 1024];
77 +}
78 +
79 +- (instancetype)initWithMemoryCapacity:(UInt64)memoryCapacity preferredMemoryCapacity:(UInt64)preferredMemoryCapacity {
80 + if (self = [super init]) {
81 + self.memoryCapacity = memoryCapacity;
82 + self.preferredMemoryUsageAfterPurge = preferredMemoryCapacity;
83 + self.cachedImages = [[NSMutableDictionary alloc] init];
84 +
85 + NSString *queueName = [NSString stringWithFormat:@"com.alamofire.autopurgingimagecache-%@", [[NSUUID UUID] UUIDString]];
86 + self.synchronizationQueue = dispatch_queue_create([queueName cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_CONCURRENT);
87 +
88 + [[NSNotificationCenter defaultCenter]
89 + addObserver:self
90 + selector:@selector(removeAllImages)
91 + name:UIApplicationDidReceiveMemoryWarningNotification
92 + object:nil];
93 +
94 + }
95 + return self;
96 +}
97 +
98 +- (void)dealloc {
99 + [[NSNotificationCenter defaultCenter] removeObserver:self];
100 +}
101 +
102 +- (UInt64)memoryUsage {
103 + __block UInt64 result = 0;
104 + dispatch_sync(self.synchronizationQueue, ^{
105 + result = self.currentMemoryUsage;
106 + });
107 + return result;
108 +}
109 +
110 +- (void)addImage:(UIImage *)image withIdentifier:(NSString *)identifier {
111 + dispatch_barrier_async(self.synchronizationQueue, ^{
112 + AFCachedImage *cacheImage = [[AFCachedImage alloc] initWithImage:image identifier:identifier];
113 +
114 + AFCachedImage *previousCachedImage = self.cachedImages[identifier];
115 + if (previousCachedImage != nil) {
116 + self.currentMemoryUsage -= previousCachedImage.totalBytes;
117 + }
118 +
119 + self.cachedImages[identifier] = cacheImage;
120 + self.currentMemoryUsage += cacheImage.totalBytes;
121 + });
122 +
123 + dispatch_barrier_async(self.synchronizationQueue, ^{
124 + if (self.currentMemoryUsage > self.memoryCapacity) {
125 + UInt64 bytesToPurge = self.currentMemoryUsage - self.preferredMemoryUsageAfterPurge;
126 + NSMutableArray <AFCachedImage*> *sortedImages = [NSMutableArray arrayWithArray:self.cachedImages.allValues];
127 + NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"lastAccessDate"
128 + ascending:YES];
129 + [sortedImages sortUsingDescriptors:@[sortDescriptor]];
130 +
131 + UInt64 bytesPurged = 0;
132 +
133 + for (AFCachedImage *cachedImage in sortedImages) {
134 + [self.cachedImages removeObjectForKey:cachedImage.identifier];
135 + bytesPurged += cachedImage.totalBytes;
136 + if (bytesPurged >= bytesToPurge) {
137 + break ;
138 + }
139 + }
140 + self.currentMemoryUsage -= bytesPurged;
141 + }
142 + });
143 +}
144 +
145 +- (BOOL)removeImageWithIdentifier:(NSString *)identifier {
146 + __block BOOL removed = NO;
147 + dispatch_barrier_sync(self.synchronizationQueue, ^{
148 + AFCachedImage *cachedImage = self.cachedImages[identifier];
149 + if (cachedImage != nil) {
150 + [self.cachedImages removeObjectForKey:identifier];
151 + self.currentMemoryUsage -= cachedImage.totalBytes;
152 + removed = YES;
153 + }
154 + });
155 + return removed;
156 +}
157 +
158 +- (BOOL)removeAllImages {
159 + __block BOOL removed = NO;
160 + dispatch_barrier_sync(self.synchronizationQueue, ^{
161 + if (self.cachedImages.count > 0) {
162 + [self.cachedImages removeAllObjects];
163 + self.currentMemoryUsage = 0;
164 + removed = YES;
165 + }
166 + });
167 + return removed;
168 +}
169 +
170 +- (nullable UIImage *)imageWithIdentifier:(NSString *)identifier {
171 + __block UIImage *image = nil;
172 + dispatch_sync(self.synchronizationQueue, ^{
173 + AFCachedImage *cachedImage = self.cachedImages[identifier];
174 + image = [cachedImage accessImage];
175 + });
176 + return image;
177 +}
178 +
179 +- (void)addImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier {
180 + [self addImage:image withIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]];
181 +}
182 +
183 +- (BOOL)removeImageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier {
184 + return [self removeImageWithIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]];
185 +}
186 +
187 +- (nullable UIImage *)imageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier {
188 + return [self imageWithIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]];
189 +}
190 +
191 +- (NSString *)imageCacheKeyFromURLRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)additionalIdentifier {
192 + NSString *key = request.URL.absoluteString;
193 + if (additionalIdentifier != nil) {
194 + key = [key stringByAppendingString:additionalIdentifier];
195 + }
196 + return key;
197 +}
198 +
199 +@end
200 +
201 +#endif
1 +// AFImageDownloader.h
2 +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 +//
4 +// Permission is hereby granted, free of charge, to any person obtaining a copy
5 +// of this software and associated documentation files (the "Software"), to deal
6 +// in the Software without restriction, including without limitation the rights
7 +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 +// copies of the Software, and to permit persons to whom the Software is
9 +// furnished to do so, subject to the following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included in
12 +// all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 +// THE SOFTWARE.
21 +
22 +#import <TargetConditionals.h>
23 +
24 +#if TARGET_OS_IOS || TARGET_OS_TV
25 +
26 +#import <Foundation/Foundation.h>
27 +#import "AFAutoPurgingImageCache.h"
28 +#import "AFHTTPSessionManager.h"
29 +
30 +NS_ASSUME_NONNULL_BEGIN
31 +
32 +typedef NS_ENUM(NSInteger, AFImageDownloadPrioritization) {
33 + AFImageDownloadPrioritizationFIFO,
34 + AFImageDownloadPrioritizationLIFO
35 +};
36 +
37 +/**
38 + 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.
39 + */
40 +@interface AFImageDownloadReceipt : NSObject
41 +
42 +/**
43 + The data task created by the `AFImageDownloader`.
44 +*/
45 +@property (nonatomic, strong) NSURLSessionDataTask *task;
46 +
47 +/**
48 + The unique identifier for the success and failure blocks when duplicate requests are made.
49 + */
50 +@property (nonatomic, strong) NSUUID *receiptID;
51 +@end
52 +
53 +/** 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.
54 + */
55 +@interface AFImageDownloader : NSObject
56 +
57 +/**
58 + The image cache used to store all downloaded images in. `AFAutoPurgingImageCache` by default.
59 + */
60 +@property (nonatomic, strong, nullable) id <AFImageRequestCache> imageCache;
61 +
62 +/**
63 + The `AFHTTPSessionManager` used to download images. By default, this is configured with an `AFImageResponseSerializer`, and a shared `NSURLCache` for all image downloads.
64 + */
65 +@property (nonatomic, strong) AFHTTPSessionManager *sessionManager;
66 +
67 +/**
68 + Defines the order prioritization of incoming download requests being inserted into the queue. `AFImageDownloadPrioritizationFIFO` by default.
69 + */
70 +@property (nonatomic, assign) AFImageDownloadPrioritization downloadPrioritizaton;
71 +
72 +/**
73 + The shared default instance of `AFImageDownloader` initialized with default values.
74 + */
75 ++ (instancetype)defaultInstance;
76 +
77 +/**
78 + Creates a default `NSURLCache` with common usage parameter values.
79 +
80 + @returns The default `NSURLCache` instance.
81 + */
82 ++ (NSURLCache *)defaultURLCache;
83 +
84 +/**
85 + Default initializer
86 +
87 + @return An instance of `AFImageDownloader` initialized with default values.
88 + */
89 +- (instancetype)init;
90 +
91 +/**
92 + Initializes the `AFImageDownloader` instance with the given session manager, download prioritization, maximum active download count and image cache.
93 +
94 + @param sessionManager The session manager to use to download images.
95 + @param downloadPrioritization The download prioritization of the download queue.
96 + @param maximumActiveDownloads The maximum number of active downloads allowed at any given time. Recommend `4`.
97 + @param imageCache The image cache used to store all downloaded images in.
98 +
99 + @return The new `AFImageDownloader` instance.
100 + */
101 +- (instancetype)initWithSessionManager:(AFHTTPSessionManager *)sessionManager
102 + downloadPrioritization:(AFImageDownloadPrioritization)downloadPrioritization
103 + maximumActiveDownloads:(NSInteger)maximumActiveDownloads
104 + imageCache:(nullable id <AFImageRequestCache>)imageCache;
105 +
106 +/**
107 + Creates a data task using the `sessionManager` instance for the specified URL request.
108 +
109 + If the same data task is already in the queue or currently being downloaded, the success and failure blocks are
110 + appended to the already existing task. Once the task completes, all success or failure blocks attached to the
111 + task are executed in the order they were added.
112 +
113 + @param request The URL request.
114 + @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`.
115 + @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.
116 +
117 + @return The image download receipt for the data task if available. `nil` if the image is stored in the cache.
118 + cache and the URL request cache policy allows the cache to be used.
119 + */
120 +- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request
121 + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success
122 + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure;
123 +
124 +/**
125 + Creates a data task using the `sessionManager` instance for the specified URL request.
126 +
127 + If the same data task is already in the queue or currently being downloaded, the success and failure blocks are
128 + appended to the already existing task. Once the task completes, all success or failure blocks attached to the
129 + task are executed in the order they were added.
130 +
131 + @param request The URL request.
132 + @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.
133 + @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`.
134 + @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.
135 +
136 + @return The image download receipt for the data task if available. `nil` if the image is stored in the cache.
137 + cache and the URL request cache policy allows the cache to be used.
138 + */
139 +- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request
140 + withReceiptID:(NSUUID *)receiptID
141 + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success
142 + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure;
143 +
144 +/**
145 + Cancels the data task in the receipt by removing the corresponding success and failure blocks and cancelling the data task if necessary.
146 +
147 + 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.
148 +
149 + @param imageDownloadReceipt The image download receipt to cancel.
150 + */
151 +- (void)cancelTaskForImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt;
152 +
153 +@end
154 +
155 +#endif
156 +
157 +NS_ASSUME_NONNULL_END
1 +// AFImageDownloader.m
2 +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 +//
4 +// Permission is hereby granted, free of charge, to any person obtaining a copy
5 +// of this software and associated documentation files (the "Software"), to deal
6 +// in the Software without restriction, including without limitation the rights
7 +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 +// copies of the Software, and to permit persons to whom the Software is
9 +// furnished to do so, subject to the following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included in
12 +// all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 +// THE SOFTWARE.
21 +
22 +#import <TargetConditionals.h>
23 +
24 +#if TARGET_OS_IOS || TARGET_OS_TV
25 +
26 +#import "AFImageDownloader.h"
27 +#import "AFHTTPSessionManager.h"
28 +
29 +@interface AFImageDownloaderResponseHandler : NSObject
30 +@property (nonatomic, strong) NSUUID *uuid;
31 +@property (nonatomic, copy) void (^successBlock)(NSURLRequest*, NSHTTPURLResponse*, UIImage*);
32 +@property (nonatomic, copy) void (^failureBlock)(NSURLRequest*, NSHTTPURLResponse*, NSError*);
33 +@end
34 +
35 +@implementation AFImageDownloaderResponseHandler
36 +
37 +- (instancetype)initWithUUID:(NSUUID *)uuid
38 + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success
39 + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure {
40 + if (self = [self init]) {
41 + self.uuid = uuid;
42 + self.successBlock = success;
43 + self.failureBlock = failure;
44 + }
45 + return self;
46 +}
47 +
48 +- (NSString *)description {
49 + return [NSString stringWithFormat: @"<AFImageDownloaderResponseHandler>UUID: %@", [self.uuid UUIDString]];
50 +}
51 +
52 +@end
53 +
54 +@interface AFImageDownloaderMergedTask : NSObject
55 +@property (nonatomic, strong) NSString *URLIdentifier;
56 +@property (nonatomic, strong) NSUUID *identifier;
57 +@property (nonatomic, strong) NSURLSessionDataTask *task;
58 +@property (nonatomic, strong) NSMutableArray <AFImageDownloaderResponseHandler*> *responseHandlers;
59 +
60 +@end
61 +
62 +@implementation AFImageDownloaderMergedTask
63 +
64 +- (instancetype)initWithURLIdentifier:(NSString *)URLIdentifier identifier:(NSUUID *)identifier task:(NSURLSessionDataTask *)task {
65 + if (self = [self init]) {
66 + self.URLIdentifier = URLIdentifier;
67 + self.task = task;
68 + self.identifier = identifier;
69 + self.responseHandlers = [[NSMutableArray alloc] init];
70 + }
71 + return self;
72 +}
73 +
74 +- (void)addResponseHandler:(AFImageDownloaderResponseHandler*)handler {
75 + [self.responseHandlers addObject:handler];
76 +}
77 +
78 +- (void)removeResponseHandler:(AFImageDownloaderResponseHandler*)handler {
79 + [self.responseHandlers removeObject:handler];
80 +}
81 +
82 +@end
83 +
84 +@implementation AFImageDownloadReceipt
85 +
86 +- (instancetype)initWithReceiptID:(NSUUID *)receiptID task:(NSURLSessionDataTask *)task {
87 + if (self = [self init]) {
88 + self.receiptID = receiptID;
89 + self.task = task;
90 + }
91 + return self;
92 +}
93 +
94 +@end
95 +
96 +@interface AFImageDownloader ()
97 +
98 +@property (nonatomic, strong) dispatch_queue_t synchronizationQueue;
99 +@property (nonatomic, strong) dispatch_queue_t responseQueue;
100 +
101 +@property (nonatomic, assign) NSInteger maximumActiveDownloads;
102 +@property (nonatomic, assign) NSInteger activeRequestCount;
103 +
104 +@property (nonatomic, strong) NSMutableArray *queuedMergedTasks;
105 +@property (nonatomic, strong) NSMutableDictionary *mergedTasks;
106 +
107 +@end
108 +
109 +
110 +@implementation AFImageDownloader
111 +
112 ++ (NSURLCache *)defaultURLCache {
113 + // It's been discovered that a crash will occur on certain versions
114 + // of iOS if you customize the cache.
115 + //
116 + // More info can be found here: https://devforums.apple.com/message/1102182#1102182
117 + //
118 + // When iOS 7 support is dropped, this should be modified to use
119 + // NSProcessInfo methods instead.
120 + if ([[[UIDevice currentDevice] systemVersion] compare:@"8.2" options:NSNumericSearch] == NSOrderedAscending) {
121 + return [NSURLCache sharedURLCache];
122 + }
123 + return [[NSURLCache alloc] initWithMemoryCapacity:20 * 1024 * 1024
124 + diskCapacity:150 * 1024 * 1024
125 + diskPath:@"com.alamofire.imagedownloader"];
126 +}
127 +
128 ++ (NSURLSessionConfiguration *)defaultURLSessionConfiguration {
129 + NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
130 +
131 + //TODO set the default HTTP headers
132 +
133 + configuration.HTTPShouldSetCookies = YES;
134 + configuration.HTTPShouldUsePipelining = NO;
135 +
136 + configuration.requestCachePolicy = NSURLRequestUseProtocolCachePolicy;
137 + configuration.allowsCellularAccess = YES;
138 + configuration.timeoutIntervalForRequest = 60.0;
139 + configuration.URLCache = [AFImageDownloader defaultURLCache];
140 +
141 + return configuration;
142 +}
143 +
144 +- (instancetype)init {
145 + NSURLSessionConfiguration *defaultConfiguration = [self.class defaultURLSessionConfiguration];
146 + AFHTTPSessionManager *sessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:defaultConfiguration];
147 + sessionManager.responseSerializer = [AFImageResponseSerializer serializer];
148 +
149 + return [self initWithSessionManager:sessionManager
150 + downloadPrioritization:AFImageDownloadPrioritizationFIFO
151 + maximumActiveDownloads:4
152 + imageCache:[[AFAutoPurgingImageCache alloc] init]];
153 +}
154 +
155 +- (instancetype)initWithSessionManager:(AFHTTPSessionManager *)sessionManager
156 + downloadPrioritization:(AFImageDownloadPrioritization)downloadPrioritization
157 + maximumActiveDownloads:(NSInteger)maximumActiveDownloads
158 + imageCache:(id <AFImageRequestCache>)imageCache {
159 + if (self = [super init]) {
160 + self.sessionManager = sessionManager;
161 +
162 + self.downloadPrioritizaton = downloadPrioritization;
163 + self.maximumActiveDownloads = maximumActiveDownloads;
164 + self.imageCache = imageCache;
165 +
166 + self.queuedMergedTasks = [[NSMutableArray alloc] init];
167 + self.mergedTasks = [[NSMutableDictionary alloc] init];
168 + self.activeRequestCount = 0;
169 +
170 + NSString *name = [NSString stringWithFormat:@"com.alamofire.imagedownloader.synchronizationqueue-%@", [[NSUUID UUID] UUIDString]];
171 + self.synchronizationQueue = dispatch_queue_create([name cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_SERIAL);
172 +
173 + name = [NSString stringWithFormat:@"com.alamofire.imagedownloader.responsequeue-%@", [[NSUUID UUID] UUIDString]];
174 + self.responseQueue = dispatch_queue_create([name cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_CONCURRENT);
175 + }
176 +
177 + return self;
178 +}
179 +
180 ++ (instancetype)defaultInstance {
181 + static AFImageDownloader *sharedInstance = nil;
182 + static dispatch_once_t onceToken;
183 + dispatch_once(&onceToken, ^{
184 + sharedInstance = [[self alloc] init];
185 + });
186 + return sharedInstance;
187 +}
188 +
189 +- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request
190 + success:(void (^)(NSURLRequest * _Nonnull, NSHTTPURLResponse * _Nullable, UIImage * _Nonnull))success
191 + failure:(void (^)(NSURLRequest * _Nonnull, NSHTTPURLResponse * _Nullable, NSError * _Nonnull))failure {
192 + return [self downloadImageForURLRequest:request withReceiptID:[NSUUID UUID] success:success failure:failure];
193 +}
194 +
195 +- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request
196 + withReceiptID:(nonnull NSUUID *)receiptID
197 + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success
198 + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure {
199 + __block NSURLSessionDataTask *task = nil;
200 + dispatch_sync(self.synchronizationQueue, ^{
201 + NSString *URLIdentifier = request.URL.absoluteString;
202 + if (URLIdentifier == nil) {
203 + if (failure) {
204 + NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorBadURL userInfo:nil];
205 + dispatch_async(dispatch_get_main_queue(), ^{
206 + failure(request, nil, error);
207 + });
208 + }
209 + return;
210 + }
211 +
212 + // 1) Append the success and failure blocks to a pre-existing request if it already exists
213 + AFImageDownloaderMergedTask *existingMergedTask = self.mergedTasks[URLIdentifier];
214 + if (existingMergedTask != nil) {
215 + AFImageDownloaderResponseHandler *handler = [[AFImageDownloaderResponseHandler alloc] initWithUUID:receiptID success:success failure:failure];
216 + [existingMergedTask addResponseHandler:handler];
217 + task = existingMergedTask.task;
218 + return;
219 + }
220 +
221 + // 2) Attempt to load the image from the image cache if the cache policy allows it
222 + switch (request.cachePolicy) {
223 + case NSURLRequestUseProtocolCachePolicy:
224 + case NSURLRequestReturnCacheDataElseLoad:
225 + case NSURLRequestReturnCacheDataDontLoad: {
226 + UIImage *cachedImage = [self.imageCache imageforRequest:request withAdditionalIdentifier:nil];
227 + if (cachedImage != nil) {
228 + if (success) {
229 + dispatch_async(dispatch_get_main_queue(), ^{
230 + success(request, nil, cachedImage);
231 + });
232 + }
233 + return;
234 + }
235 + break;
236 + }
237 + default:
238 + break;
239 + }
240 +
241 + // 3) Create the request and set up authentication, validation and response serialization
242 + NSUUID *mergedTaskIdentifier = [NSUUID UUID];
243 + NSURLSessionDataTask *createdTask;
244 + __weak __typeof__(self) weakSelf = self;
245 +
246 + createdTask = [self.sessionManager
247 + dataTaskWithRequest:request
248 + uploadProgress:nil
249 + downloadProgress:nil
250 + completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
251 + dispatch_async(self.responseQueue, ^{
252 + __strong __typeof__(weakSelf) strongSelf = weakSelf;
253 + AFImageDownloaderMergedTask *mergedTask = self.mergedTasks[URLIdentifier];
254 + if ([mergedTask.identifier isEqual:mergedTaskIdentifier]) {
255 + mergedTask = [strongSelf safelyRemoveMergedTaskWithURLIdentifier:URLIdentifier];
256 + if (error) {
257 + for (AFImageDownloaderResponseHandler *handler in mergedTask.responseHandlers) {
258 + if (handler.failureBlock) {
259 + dispatch_async(dispatch_get_main_queue(), ^{
260 + handler.failureBlock(request, (NSHTTPURLResponse*)response, error);
261 + });
262 + }
263 + }
264 + } else {
265 + [strongSelf.imageCache addImage:responseObject forRequest:request withAdditionalIdentifier:nil];
266 +
267 + for (AFImageDownloaderResponseHandler *handler in mergedTask.responseHandlers) {
268 + if (handler.successBlock) {
269 + dispatch_async(dispatch_get_main_queue(), ^{
270 + handler.successBlock(request, (NSHTTPURLResponse*)response, responseObject);
271 + });
272 + }
273 + }
274 +
275 + }
276 + }
277 + [strongSelf safelyDecrementActiveTaskCount];
278 + [strongSelf safelyStartNextTaskIfNecessary];
279 + });
280 + }];
281 +
282 + // 4) Store the response handler for use when the request completes
283 + AFImageDownloaderResponseHandler *handler = [[AFImageDownloaderResponseHandler alloc] initWithUUID:receiptID
284 + success:success
285 + failure:failure];
286 + AFImageDownloaderMergedTask *mergedTask = [[AFImageDownloaderMergedTask alloc]
287 + initWithURLIdentifier:URLIdentifier
288 + identifier:mergedTaskIdentifier
289 + task:createdTask];
290 + [mergedTask addResponseHandler:handler];
291 + self.mergedTasks[URLIdentifier] = mergedTask;
292 +
293 + // 5) Either start the request or enqueue it depending on the current active request count
294 + if ([self isActiveRequestCountBelowMaximumLimit]) {
295 + [self startMergedTask:mergedTask];
296 + } else {
297 + [self enqueueMergedTask:mergedTask];
298 + }
299 +
300 + task = mergedTask.task;
301 + });
302 + if (task) {
303 + return [[AFImageDownloadReceipt alloc] initWithReceiptID:receiptID task:task];
304 + } else {
305 + return nil;
306 + }
307 +}
308 +
309 +- (void)cancelTaskForImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt {
310 + dispatch_sync(self.synchronizationQueue, ^{
311 + NSString *URLIdentifier = imageDownloadReceipt.task.originalRequest.URL.absoluteString;
312 + AFImageDownloaderMergedTask *mergedTask = self.mergedTasks[URLIdentifier];
313 + NSUInteger index = [mergedTask.responseHandlers indexOfObjectPassingTest:^BOOL(AFImageDownloaderResponseHandler * _Nonnull handler, __unused NSUInteger idx, __unused BOOL * _Nonnull stop) {
314 + return handler.uuid == imageDownloadReceipt.receiptID;
315 + }];
316 +
317 + if (index != NSNotFound) {
318 + AFImageDownloaderResponseHandler *handler = mergedTask.responseHandlers[index];
319 + [mergedTask removeResponseHandler:handler];
320 + NSString *failureReason = [NSString stringWithFormat:@"ImageDownloader cancelled URL request: %@",imageDownloadReceipt.task.originalRequest.URL.absoluteString];
321 + NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey:failureReason};
322 + NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo];
323 + if (handler.failureBlock) {
324 + dispatch_async(dispatch_get_main_queue(), ^{
325 + handler.failureBlock(imageDownloadReceipt.task.originalRequest, nil, error);
326 + });
327 + }
328 + }
329 +
330 + if (mergedTask.responseHandlers.count == 0 && mergedTask.task.state == NSURLSessionTaskStateSuspended) {
331 + [mergedTask.task cancel];
332 + [self removeMergedTaskWithURLIdentifier:URLIdentifier];
333 + }
334 + });
335 +}
336 +
337 +- (AFImageDownloaderMergedTask*)safelyRemoveMergedTaskWithURLIdentifier:(NSString *)URLIdentifier {
338 + __block AFImageDownloaderMergedTask *mergedTask = nil;
339 + dispatch_sync(self.synchronizationQueue, ^{
340 + mergedTask = [self removeMergedTaskWithURLIdentifier:URLIdentifier];
341 + });
342 + return mergedTask;
343 +}
344 +
345 +//This method should only be called from safely within the synchronizationQueue
346 +- (AFImageDownloaderMergedTask *)removeMergedTaskWithURLIdentifier:(NSString *)URLIdentifier {
347 + AFImageDownloaderMergedTask *mergedTask = self.mergedTasks[URLIdentifier];
348 + [self.mergedTasks removeObjectForKey:URLIdentifier];
349 + return mergedTask;
350 +}
351 +
352 +- (void)safelyDecrementActiveTaskCount {
353 + dispatch_sync(self.synchronizationQueue, ^{
354 + if (self.activeRequestCount > 0) {
355 + self.activeRequestCount -= 1;
356 + }
357 + });
358 +}
359 +
360 +- (void)safelyStartNextTaskIfNecessary {
361 + dispatch_sync(self.synchronizationQueue, ^{
362 + if ([self isActiveRequestCountBelowMaximumLimit]) {
363 + while (self.queuedMergedTasks.count > 0) {
364 + AFImageDownloaderMergedTask *mergedTask = [self dequeueMergedTask];
365 + if (mergedTask.task.state == NSURLSessionTaskStateSuspended) {
366 + [self startMergedTask:mergedTask];
367 + break;
368 + }
369 + }
370 + }
371 + });
372 +}
373 +
374 +- (void)startMergedTask:(AFImageDownloaderMergedTask *)mergedTask {
375 + [mergedTask.task resume];
376 + ++self.activeRequestCount;
377 +}
378 +
379 +- (void)enqueueMergedTask:(AFImageDownloaderMergedTask *)mergedTask {
380 + switch (self.downloadPrioritizaton) {
381 + case AFImageDownloadPrioritizationFIFO:
382 + [self.queuedMergedTasks addObject:mergedTask];
383 + break;
384 + case AFImageDownloadPrioritizationLIFO:
385 + [self.queuedMergedTasks insertObject:mergedTask atIndex:0];
386 + break;
387 + }
388 +}
389 +
390 +- (AFImageDownloaderMergedTask *)dequeueMergedTask {
391 + AFImageDownloaderMergedTask *mergedTask = nil;
392 + mergedTask = [self.queuedMergedTasks firstObject];
393 + [self.queuedMergedTasks removeObject:mergedTask];
394 + return mergedTask;
395 +}
396 +
397 +- (BOOL)isActiveRequestCountBelowMaximumLimit {
398 + return self.activeRequestCount < self.maximumActiveDownloads;
399 +}
400 +
401 +@end
402 +
403 +#endif
1 +// AFNetworkActivityIndicatorManager.h
2 +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 +//
4 +// Permission is hereby granted, free of charge, to any person obtaining a copy
5 +// of this software and associated documentation files (the "Software"), to deal
6 +// in the Software without restriction, including without limitation the rights
7 +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 +// copies of the Software, and to permit persons to whom the Software is
9 +// furnished to do so, subject to the following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included in
12 +// all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 +// THE SOFTWARE.
21 +
22 +#import <Foundation/Foundation.h>
23 +
24 +#import <TargetConditionals.h>
25 +
26 +#if TARGET_OS_IOS
27 +
28 +#import <UIKit/UIKit.h>
29 +
30 +NS_ASSUME_NONNULL_BEGIN
31 +
32 +/**
33 + `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.
34 +
35 + 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:
36 +
37 + [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
38 +
39 + 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.
40 +
41 + See the Apple Human Interface Guidelines section about the Network Activity Indicator for more information:
42 + http://developer.apple.com/library/iOS/#documentation/UserExperience/Conceptual/MobileHIG/UIElementGuidelines/UIElementGuidelines.html#//apple_ref/doc/uid/TP40006556-CH13-SW44
43 + */
44 +NS_EXTENSION_UNAVAILABLE_IOS("Use view controller based solutions where appropriate instead.")
45 +@interface AFNetworkActivityIndicatorManager : NSObject
46 +
47 +/**
48 + A Boolean value indicating whether the manager is enabled.
49 +
50 + If YES, the manager will change status bar network activity indicator according to network operation notifications it receives. The default value is NO.
51 + */
52 +@property (nonatomic, assign, getter = isEnabled) BOOL enabled;
53 +
54 +/**
55 + A Boolean value indicating whether the network activity indicator manager is currently active.
56 +*/
57 +@property (readonly, nonatomic, assign, getter=isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible;
58 +
59 +/**
60 + 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.
61 +
62 + Apple's HIG describes the following:
63 +
64 + > 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.
65 +
66 + */
67 +@property (nonatomic, assign) NSTimeInterval activationDelay;
68 +
69 +/**
70 + 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.
71 + */
72 +
73 +@property (nonatomic, assign) NSTimeInterval completionDelay;
74 +
75 +/**
76 + Returns the shared network activity indicator manager object for the system.
77 +
78 + @return The systemwide network activity indicator manager.
79 + */
80 ++ (instancetype)sharedManager;
81 +
82 +/**
83 + Increments the number of active network requests. If this number was zero before incrementing, this will start animating the status bar network activity indicator.
84 + */
85 +- (void)incrementActivityCount;
86 +
87 +/**
88 + Decrements the number of active network requests. If this number becomes zero after decrementing, this will stop animating the status bar network activity indicator.
89 + */
90 +- (void)decrementActivityCount;
91 +
92 +/**
93 + 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.
94 +
95 + @param block A block to be executed when the network activity indicator status changes.
96 + */
97 +- (void)setNetworkingActivityActionWithBlock:(nullable void (^)(BOOL networkActivityIndicatorVisible))block;
98 +
99 +@end
100 +
101 +NS_ASSUME_NONNULL_END
102 +
103 +#endif
1 +// AFNetworkActivityIndicatorManager.m
2 +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 +//
4 +// Permission is hereby granted, free of charge, to any person obtaining a copy
5 +// of this software and associated documentation files (the "Software"), to deal
6 +// in the Software without restriction, including without limitation the rights
7 +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 +// copies of the Software, and to permit persons to whom the Software is
9 +// furnished to do so, subject to the following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included in
12 +// all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 +// THE SOFTWARE.
21 +
22 +#import "AFNetworkActivityIndicatorManager.h"
23 +
24 +#if TARGET_OS_IOS
25 +#import "AFURLSessionManager.h"
26 +
27 +typedef NS_ENUM(NSInteger, AFNetworkActivityManagerState) {
28 + AFNetworkActivityManagerStateNotActive,
29 + AFNetworkActivityManagerStateDelayingStart,
30 + AFNetworkActivityManagerStateActive,
31 + AFNetworkActivityManagerStateDelayingEnd
32 +};
33 +
34 +static NSTimeInterval const kDefaultAFNetworkActivityManagerActivationDelay = 1.0;
35 +static NSTimeInterval const kDefaultAFNetworkActivityManagerCompletionDelay = 0.17;
36 +
37 +static NSURLRequest * AFNetworkRequestFromNotification(NSNotification *notification) {
38 + if ([[notification object] respondsToSelector:@selector(originalRequest)]) {
39 + return [(NSURLSessionTask *)[notification object] originalRequest];
40 + } else {
41 + return nil;
42 + }
43 +}
44 +
45 +typedef void (^AFNetworkActivityActionBlock)(BOOL networkActivityIndicatorVisible);
46 +
47 +@interface AFNetworkActivityIndicatorManager ()
48 +@property (readwrite, nonatomic, assign) NSInteger activityCount;
49 +@property (readwrite, nonatomic, strong) NSTimer *activationDelayTimer;
50 +@property (readwrite, nonatomic, strong) NSTimer *completionDelayTimer;
51 +@property (readonly, nonatomic, getter = isNetworkActivityOccurring) BOOL networkActivityOccurring;
52 +@property (nonatomic, copy) AFNetworkActivityActionBlock networkActivityActionBlock;
53 +@property (nonatomic, assign) AFNetworkActivityManagerState currentState;
54 +@property (nonatomic, assign, getter=isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible;
55 +
56 +- (void)updateCurrentStateForNetworkActivityChange;
57 +@end
58 +
59 +@implementation AFNetworkActivityIndicatorManager
60 +
61 ++ (instancetype)sharedManager {
62 + static AFNetworkActivityIndicatorManager *_sharedManager = nil;
63 + static dispatch_once_t oncePredicate;
64 + dispatch_once(&oncePredicate, ^{
65 + _sharedManager = [[self alloc] init];
66 + });
67 +
68 + return _sharedManager;
69 +}
70 +
71 +- (instancetype)init {
72 + self = [super init];
73 + if (!self) {
74 + return nil;
75 + }
76 + self.currentState = AFNetworkActivityManagerStateNotActive;
77 + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidStart:) name:AFNetworkingTaskDidResumeNotification object:nil];
78 + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingTaskDidSuspendNotification object:nil];
79 + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingTaskDidCompleteNotification object:nil];
80 + self.activationDelay = kDefaultAFNetworkActivityManagerActivationDelay;
81 + self.completionDelay = kDefaultAFNetworkActivityManagerCompletionDelay;
82 +
83 + return self;
84 +}
85 +
86 +- (void)dealloc {
87 + [[NSNotificationCenter defaultCenter] removeObserver:self];
88 +
89 + [_activationDelayTimer invalidate];
90 + [_completionDelayTimer invalidate];
91 +}
92 +
93 +- (void)setEnabled:(BOOL)enabled {
94 + _enabled = enabled;
95 + if (enabled == NO) {
96 + [self setCurrentState:AFNetworkActivityManagerStateNotActive];
97 + }
98 +}
99 +
100 +- (void)setNetworkingActivityActionWithBlock:(void (^)(BOOL networkActivityIndicatorVisible))block {
101 + self.networkActivityActionBlock = block;
102 +}
103 +
104 +- (BOOL)isNetworkActivityOccurring {
105 + @synchronized(self) {
106 + return self.activityCount > 0;
107 + }
108 +}
109 +
110 +- (void)setNetworkActivityIndicatorVisible:(BOOL)networkActivityIndicatorVisible {
111 + if (_networkActivityIndicatorVisible != networkActivityIndicatorVisible) {
112 + [self willChangeValueForKey:@"networkActivityIndicatorVisible"];
113 + @synchronized(self) {
114 + _networkActivityIndicatorVisible = networkActivityIndicatorVisible;
115 + }
116 + [self didChangeValueForKey:@"networkActivityIndicatorVisible"];
117 + if (self.networkActivityActionBlock) {
118 + self.networkActivityActionBlock(networkActivityIndicatorVisible);
119 + } else {
120 + [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:networkActivityIndicatorVisible];
121 + }
122 + }
123 +}
124 +
125 +- (void)setActivityCount:(NSInteger)activityCount {
126 + @synchronized(self) {
127 + _activityCount = activityCount;
128 + }
129 +
130 + dispatch_async(dispatch_get_main_queue(), ^{
131 + [self updateCurrentStateForNetworkActivityChange];
132 + });
133 +}
134 +
135 +- (void)incrementActivityCount {
136 + [self willChangeValueForKey:@"activityCount"];
137 + @synchronized(self) {
138 + _activityCount++;
139 + }
140 + [self didChangeValueForKey:@"activityCount"];
141 +
142 + dispatch_async(dispatch_get_main_queue(), ^{
143 + [self updateCurrentStateForNetworkActivityChange];
144 + });
145 +}
146 +
147 +- (void)decrementActivityCount {
148 + [self willChangeValueForKey:@"activityCount"];
149 + @synchronized(self) {
150 + _activityCount = MAX(_activityCount - 1, 0);
151 + }
152 + [self didChangeValueForKey:@"activityCount"];
153 +
154 + dispatch_async(dispatch_get_main_queue(), ^{
155 + [self updateCurrentStateForNetworkActivityChange];
156 + });
157 +}
158 +
159 +- (void)networkRequestDidStart:(NSNotification *)notification {
160 + if ([AFNetworkRequestFromNotification(notification) URL]) {
161 + [self incrementActivityCount];
162 + }
163 +}
164 +
165 +- (void)networkRequestDidFinish:(NSNotification *)notification {
166 + if ([AFNetworkRequestFromNotification(notification) URL]) {
167 + [self decrementActivityCount];
168 + }
169 +}
170 +
171 +#pragma mark - Internal State Management
172 +- (void)setCurrentState:(AFNetworkActivityManagerState)currentState {
173 + @synchronized(self) {
174 + if (_currentState != currentState) {
175 + [self willChangeValueForKey:@"currentState"];
176 + _currentState = currentState;
177 + switch (currentState) {
178 + case AFNetworkActivityManagerStateNotActive:
179 + [self cancelActivationDelayTimer];
180 + [self cancelCompletionDelayTimer];
181 + [self setNetworkActivityIndicatorVisible:NO];
182 + break;
183 + case AFNetworkActivityManagerStateDelayingStart:
184 + [self startActivationDelayTimer];
185 + break;
186 + case AFNetworkActivityManagerStateActive:
187 + [self cancelCompletionDelayTimer];
188 + [self setNetworkActivityIndicatorVisible:YES];
189 + break;
190 + case AFNetworkActivityManagerStateDelayingEnd:
191 + [self startCompletionDelayTimer];
192 + break;
193 + }
194 + [self didChangeValueForKey:@"currentState"];
195 + }
196 +
197 + }
198 +}
199 +
200 +- (void)updateCurrentStateForNetworkActivityChange {
201 + if (self.enabled) {
202 + switch (self.currentState) {
203 + case AFNetworkActivityManagerStateNotActive:
204 + if (self.isNetworkActivityOccurring) {
205 + [self setCurrentState:AFNetworkActivityManagerStateDelayingStart];
206 + }
207 + break;
208 + case AFNetworkActivityManagerStateDelayingStart:
209 + //No op. Let the delay timer finish out.
210 + break;
211 + case AFNetworkActivityManagerStateActive:
212 + if (!self.isNetworkActivityOccurring) {
213 + [self setCurrentState:AFNetworkActivityManagerStateDelayingEnd];
214 + }
215 + break;
216 + case AFNetworkActivityManagerStateDelayingEnd:
217 + if (self.isNetworkActivityOccurring) {
218 + [self setCurrentState:AFNetworkActivityManagerStateActive];
219 + }
220 + break;
221 + }
222 + }
223 +}
224 +
225 +- (void)startActivationDelayTimer {
226 + self.activationDelayTimer = [NSTimer
227 + timerWithTimeInterval:self.activationDelay target:self selector:@selector(activationDelayTimerFired) userInfo:nil repeats:NO];
228 + [[NSRunLoop mainRunLoop] addTimer:self.activationDelayTimer forMode:NSRunLoopCommonModes];
229 +}
230 +
231 +- (void)activationDelayTimerFired {
232 + if (self.networkActivityOccurring) {
233 + [self setCurrentState:AFNetworkActivityManagerStateActive];
234 + } else {
235 + [self setCurrentState:AFNetworkActivityManagerStateNotActive];
236 + }
237 +}
238 +
239 +- (void)startCompletionDelayTimer {
240 + [self.completionDelayTimer invalidate];
241 + self.completionDelayTimer = [NSTimer timerWithTimeInterval:self.completionDelay target:self selector:@selector(completionDelayTimerFired) userInfo:nil repeats:NO];
242 + [[NSRunLoop mainRunLoop] addTimer:self.completionDelayTimer forMode:NSRunLoopCommonModes];
243 +}
244 +
245 +- (void)completionDelayTimerFired {
246 + [self setCurrentState:AFNetworkActivityManagerStateNotActive];
247 +}
248 +
249 +- (void)cancelActivationDelayTimer {
250 + [self.activationDelayTimer invalidate];
251 +}
252 +
253 +- (void)cancelCompletionDelayTimer {
254 + [self.completionDelayTimer invalidate];
255 +}
256 +
257 +@end
258 +
259 +#endif
1 +// UIActivityIndicatorView+AFNetworking.h
2 +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 +//
4 +// Permission is hereby granted, free of charge, to any person obtaining a copy
5 +// of this software and associated documentation files (the "Software"), to deal
6 +// in the Software without restriction, including without limitation the rights
7 +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 +// copies of the Software, and to permit persons to whom the Software is
9 +// furnished to do so, subject to the following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included in
12 +// all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 +// THE SOFTWARE.
21 +
22 +#import <Foundation/Foundation.h>
23 +
24 +#import <TargetConditionals.h>
25 +
26 +#if TARGET_OS_IOS || TARGET_OS_TV
27 +
28 +#import <UIKit/UIKit.h>
29 +
30 +/**
31 + 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.
32 + */
33 +@interface UIActivityIndicatorView (AFNetworking)
34 +
35 +///----------------------------------
36 +/// @name Animating for Session Tasks
37 +///----------------------------------
38 +
39 +/**
40 + Binds the animating state to the state of the specified task.
41 +
42 + @param task The task. If `nil`, automatic updating from any previously specified operation will be disabled.
43 + */
44 +- (void)setAnimatingWithStateOfTask:(nullable NSURLSessionTask *)task;
45 +
46 +@end
47 +
48 +#endif
1 +// UIActivityIndicatorView+AFNetworking.m
2 +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 +//
4 +// Permission is hereby granted, free of charge, to any person obtaining a copy
5 +// of this software and associated documentation files (the "Software"), to deal
6 +// in the Software without restriction, including without limitation the rights
7 +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 +// copies of the Software, and to permit persons to whom the Software is
9 +// furnished to do so, subject to the following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included in
12 +// all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 +// THE SOFTWARE.
21 +
22 +#import "UIActivityIndicatorView+AFNetworking.h"
23 +#import <objc/runtime.h>
24 +
25 +#if TARGET_OS_IOS || TARGET_OS_TV
26 +
27 +#import "AFURLSessionManager.h"
28 +
29 +@interface AFActivityIndicatorViewNotificationObserver : NSObject
30 +@property (readonly, nonatomic, weak) UIActivityIndicatorView *activityIndicatorView;
31 +- (instancetype)initWithActivityIndicatorView:(UIActivityIndicatorView *)activityIndicatorView;
32 +
33 +- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task;
34 +
35 +@end
36 +
37 +@implementation UIActivityIndicatorView (AFNetworking)
38 +
39 +- (AFActivityIndicatorViewNotificationObserver *)af_notificationObserver {
40 + AFActivityIndicatorViewNotificationObserver *notificationObserver = objc_getAssociatedObject(self, @selector(af_notificationObserver));
41 + if (notificationObserver == nil) {
42 + notificationObserver = [[AFActivityIndicatorViewNotificationObserver alloc] initWithActivityIndicatorView:self];
43 + objc_setAssociatedObject(self, @selector(af_notificationObserver), notificationObserver, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
44 + }
45 + return notificationObserver;
46 +}
47 +
48 +- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task {
49 + [[self af_notificationObserver] setAnimatingWithStateOfTask:task];
50 +}
51 +
52 +@end
53 +
54 +@implementation AFActivityIndicatorViewNotificationObserver
55 +
56 +- (instancetype)initWithActivityIndicatorView:(UIActivityIndicatorView *)activityIndicatorView
57 +{
58 + self = [super init];
59 + if (self) {
60 + _activityIndicatorView = activityIndicatorView;
61 + }
62 + return self;
63 +}
64 +
65 +- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task {
66 + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
67 +
68 + [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil];
69 + [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil];
70 + [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil];
71 +
72 + if (task) {
73 + if (task.state != NSURLSessionTaskStateCompleted) {
74 + UIActivityIndicatorView *activityIndicatorView = self.activityIndicatorView;
75 + if (task.state == NSURLSessionTaskStateRunning) {
76 + [activityIndicatorView startAnimating];
77 + } else {
78 + [activityIndicatorView stopAnimating];
79 + }
80 +
81 + [notificationCenter addObserver:self selector:@selector(af_startAnimating) name:AFNetworkingTaskDidResumeNotification object:task];
82 + [notificationCenter addObserver:self selector:@selector(af_stopAnimating) name:AFNetworkingTaskDidCompleteNotification object:task];
83 + [notificationCenter addObserver:self selector:@selector(af_stopAnimating) name:AFNetworkingTaskDidSuspendNotification object:task];
84 + }
85 + }
86 +}
87 +
88 +#pragma mark -
89 +
90 +- (void)af_startAnimating {
91 + dispatch_async(dispatch_get_main_queue(), ^{
92 + [self.activityIndicatorView startAnimating];
93 + });
94 +}
95 +
96 +- (void)af_stopAnimating {
97 + dispatch_async(dispatch_get_main_queue(), ^{
98 + [self.activityIndicatorView stopAnimating];
99 + });
100 +}
101 +
102 +#pragma mark -
103 +
104 +- (void)dealloc {
105 + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
106 +
107 + [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil];
108 + [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil];
109 + [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil];
110 +}
111 +
112 +@end
113 +
114 +#endif
1 +// UIButton+AFNetworking.h
2 +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 +//
4 +// Permission is hereby granted, free of charge, to any person obtaining a copy
5 +// of this software and associated documentation files (the "Software"), to deal
6 +// in the Software without restriction, including without limitation the rights
7 +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 +// copies of the Software, and to permit persons to whom the Software is
9 +// furnished to do so, subject to the following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included in
12 +// all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 +// THE SOFTWARE.
21 +
22 +#import <Foundation/Foundation.h>
23 +
24 +#import <TargetConditionals.h>
25 +
26 +#if TARGET_OS_IOS || TARGET_OS_TV
27 +
28 +#import <UIKit/UIKit.h>
29 +
30 +NS_ASSUME_NONNULL_BEGIN
31 +
32 +@class AFImageDownloader;
33 +
34 +/**
35 + 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.
36 +
37 + @warning Compound values for control `state` (such as `UIControlStateHighlighted | UIControlStateDisabled`) are unsupported.
38 + */
39 +@interface UIButton (AFNetworking)
40 +
41 +///------------------------------------
42 +/// @name Accessing the Image Downloader
43 +///------------------------------------
44 +
45 +/**
46 + Set the shared image downloader used to download images.
47 +
48 + @param imageDownloader The shared image downloader used to download images.
49 +*/
50 ++ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader;
51 +
52 +/**
53 + The shared image downloader used to download images.
54 + */
55 ++ (AFImageDownloader *)sharedImageDownloader;
56 +
57 +///--------------------
58 +/// @name Setting Image
59 +///--------------------
60 +
61 +/**
62 + 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.
63 +
64 + 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.
65 +
66 + @param state The control state.
67 + @param url The URL used for the image request.
68 + */
69 +- (void)setImageForState:(UIControlState)state
70 + withURL:(NSURL *)url;
71 +
72 +/**
73 + 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.
74 +
75 + 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.
76 +
77 + @param state The control state.
78 + @param url The URL used for the image request.
79 + @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.
80 + */
81 +- (void)setImageForState:(UIControlState)state
82 + withURL:(NSURL *)url
83 + placeholderImage:(nullable UIImage *)placeholderImage;
84 +
85 +/**
86 + 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.
87 +
88 + 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.
89 +
90 + 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.
91 +
92 + @param state The control state.
93 + @param urlRequest The URL request used for the image request.
94 + @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.
95 + @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`.
96 + @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.
97 + */
98 +- (void)setImageForState:(UIControlState)state
99 + withURLRequest:(NSURLRequest *)urlRequest
100 + placeholderImage:(nullable UIImage *)placeholderImage
101 + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success
102 + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure;
103 +
104 +
105 +///-------------------------------
106 +/// @name Setting Background Image
107 +///-------------------------------
108 +
109 +/**
110 + 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.
111 +
112 + 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.
113 +
114 + @param state The control state.
115 + @param url The URL used for the background image request.
116 + */
117 +- (void)setBackgroundImageForState:(UIControlState)state
118 + withURL:(NSURL *)url;
119 +
120 +/**
121 + 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.
122 +
123 + 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.
124 +
125 + @param state The control state.
126 + @param url The URL used for the background image request.
127 + @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.
128 + */
129 +- (void)setBackgroundImageForState:(UIControlState)state
130 + withURL:(NSURL *)url
131 + placeholderImage:(nullable UIImage *)placeholderImage;
132 +
133 +/**
134 + 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.
135 +
136 + 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.
137 +
138 + 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.
139 +
140 + @param state The control state.
141 + @param urlRequest The URL request used for the image request.
142 + @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.
143 + @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`.
144 + @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.
145 + */
146 +- (void)setBackgroundImageForState:(UIControlState)state
147 + withURLRequest:(NSURLRequest *)urlRequest
148 + placeholderImage:(nullable UIImage *)placeholderImage
149 + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success
150 + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure;
151 +
152 +
153 +///------------------------------
154 +/// @name Canceling Image Loading
155 +///------------------------------
156 +
157 +/**
158 + Cancels any executing image task for the specified control state of the receiver, if one exists.
159 +
160 + @param state The control state.
161 + */
162 +- (void)cancelImageDownloadTaskForState:(UIControlState)state;
163 +
164 +/**
165 + Cancels any executing background image task for the specified control state of the receiver, if one exists.
166 +
167 + @param state The control state.
168 + */
169 +- (void)cancelBackgroundImageDownloadTaskForState:(UIControlState)state;
170 +
171 +@end
172 +
173 +NS_ASSUME_NONNULL_END
174 +
175 +#endif
1 +// UIButton+AFNetworking.m
2 +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 +//
4 +// Permission is hereby granted, free of charge, to any person obtaining a copy
5 +// of this software and associated documentation files (the "Software"), to deal
6 +// in the Software without restriction, including without limitation the rights
7 +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 +// copies of the Software, and to permit persons to whom the Software is
9 +// furnished to do so, subject to the following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included in
12 +// all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 +// THE SOFTWARE.
21 +
22 +#import "UIButton+AFNetworking.h"
23 +
24 +#import <objc/runtime.h>
25 +
26 +#if TARGET_OS_IOS || TARGET_OS_TV
27 +
28 +#import "UIImageView+AFNetworking.h"
29 +#import "AFImageDownloader.h"
30 +
31 +@interface UIButton (_AFNetworking)
32 +@end
33 +
34 +@implementation UIButton (_AFNetworking)
35 +
36 +#pragma mark -
37 +
38 +static char AFImageDownloadReceiptNormal;
39 +static char AFImageDownloadReceiptHighlighted;
40 +static char AFImageDownloadReceiptSelected;
41 +static char AFImageDownloadReceiptDisabled;
42 +
43 +static const char * af_imageDownloadReceiptKeyForState(UIControlState state) {
44 + switch (state) {
45 + case UIControlStateHighlighted:
46 + return &AFImageDownloadReceiptHighlighted;
47 + case UIControlStateSelected:
48 + return &AFImageDownloadReceiptSelected;
49 + case UIControlStateDisabled:
50 + return &AFImageDownloadReceiptDisabled;
51 + case UIControlStateNormal:
52 + default:
53 + return &AFImageDownloadReceiptNormal;
54 + }
55 +}
56 +
57 +- (AFImageDownloadReceipt *)af_imageDownloadReceiptForState:(UIControlState)state {
58 + return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, af_imageDownloadReceiptKeyForState(state));
59 +}
60 +
61 +- (void)af_setImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt
62 + forState:(UIControlState)state
63 +{
64 + objc_setAssociatedObject(self, af_imageDownloadReceiptKeyForState(state), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
65 +}
66 +
67 +#pragma mark -
68 +
69 +static char AFBackgroundImageDownloadReceiptNormal;
70 +static char AFBackgroundImageDownloadReceiptHighlighted;
71 +static char AFBackgroundImageDownloadReceiptSelected;
72 +static char AFBackgroundImageDownloadReceiptDisabled;
73 +
74 +static const char * af_backgroundImageDownloadReceiptKeyForState(UIControlState state) {
75 + switch (state) {
76 + case UIControlStateHighlighted:
77 + return &AFBackgroundImageDownloadReceiptHighlighted;
78 + case UIControlStateSelected:
79 + return &AFBackgroundImageDownloadReceiptSelected;
80 + case UIControlStateDisabled:
81 + return &AFBackgroundImageDownloadReceiptDisabled;
82 + case UIControlStateNormal:
83 + default:
84 + return &AFBackgroundImageDownloadReceiptNormal;
85 + }
86 +}
87 +
88 +- (AFImageDownloadReceipt *)af_backgroundImageDownloadReceiptForState:(UIControlState)state {
89 + return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, af_backgroundImageDownloadReceiptKeyForState(state));
90 +}
91 +
92 +- (void)af_setBackgroundImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt
93 + forState:(UIControlState)state
94 +{
95 + objc_setAssociatedObject(self, af_backgroundImageDownloadReceiptKeyForState(state), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
96 +}
97 +
98 +@end
99 +
100 +#pragma mark -
101 +
102 +@implementation UIButton (AFNetworking)
103 +
104 ++ (AFImageDownloader *)sharedImageDownloader {
105 +
106 + return objc_getAssociatedObject(self, @selector(sharedImageDownloader)) ?: [AFImageDownloader defaultInstance];
107 +}
108 +
109 ++ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader {
110 + objc_setAssociatedObject(self, @selector(sharedImageDownloader), imageDownloader, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
111 +}
112 +
113 +#pragma mark -
114 +
115 +- (void)setImageForState:(UIControlState)state
116 + withURL:(NSURL *)url
117 +{
118 + [self setImageForState:state withURL:url placeholderImage:nil];
119 +}
120 +
121 +- (void)setImageForState:(UIControlState)state
122 + withURL:(NSURL *)url
123 + placeholderImage:(UIImage *)placeholderImage
124 +{
125 + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
126 + [request addValue:@"image/*" forHTTPHeaderField:@"Accept"];
127 +
128 + [self setImageForState:state withURLRequest:request placeholderImage:placeholderImage success:nil failure:nil];
129 +}
130 +
131 +- (void)setImageForState:(UIControlState)state
132 + withURLRequest:(NSURLRequest *)urlRequest
133 + placeholderImage:(nullable UIImage *)placeholderImage
134 + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success
135 + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure
136 +{
137 + if ([self isActiveTaskURLEqualToURLRequest:urlRequest forState:state]) {
138 + return;
139 + }
140 +
141 + [self cancelImageDownloadTaskForState:state];
142 +
143 + AFImageDownloader *downloader = [[self class] sharedImageDownloader];
144 + id <AFImageRequestCache> imageCache = downloader.imageCache;
145 +
146 + //Use the image from the image cache if it exists
147 + UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil];
148 + if (cachedImage) {
149 + if (success) {
150 + success(urlRequest, nil, cachedImage);
151 + } else {
152 + [self setImage:cachedImage forState:state];
153 + }
154 + [self af_setImageDownloadReceipt:nil forState:state];
155 + } else {
156 + if (placeholderImage) {
157 + [self setImage:placeholderImage forState:state];
158 + }
159 +
160 + __weak __typeof(self)weakSelf = self;
161 + NSUUID *downloadID = [NSUUID UUID];
162 + AFImageDownloadReceipt *receipt;
163 + receipt = [downloader
164 + downloadImageForURLRequest:urlRequest
165 + withReceiptID:downloadID
166 + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) {
167 + __strong __typeof(weakSelf)strongSelf = weakSelf;
168 + if ([[strongSelf af_imageDownloadReceiptForState:state].receiptID isEqual:downloadID]) {
169 + if (success) {
170 + success(request, response, responseObject);
171 + } else if(responseObject) {
172 + [strongSelf setImage:responseObject forState:state];
173 + }
174 + [strongSelf af_setImageDownloadReceipt:nil forState:state];
175 + }
176 +
177 + }
178 + failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {
179 + __strong __typeof(weakSelf)strongSelf = weakSelf;
180 + if ([[strongSelf af_imageDownloadReceiptForState:state].receiptID isEqual:downloadID]) {
181 + if (failure) {
182 + failure(request, response, error);
183 + }
184 + [strongSelf af_setImageDownloadReceipt:nil forState:state];
185 + }
186 + }];
187 +
188 + [self af_setImageDownloadReceipt:receipt forState:state];
189 + }
190 +}
191 +
192 +#pragma mark -
193 +
194 +- (void)setBackgroundImageForState:(UIControlState)state
195 + withURL:(NSURL *)url
196 +{
197 + [self setBackgroundImageForState:state withURL:url placeholderImage:nil];
198 +}
199 +
200 +- (void)setBackgroundImageForState:(UIControlState)state
201 + withURL:(NSURL *)url
202 + placeholderImage:(nullable UIImage *)placeholderImage
203 +{
204 + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
205 + [request addValue:@"image/*" forHTTPHeaderField:@"Accept"];
206 +
207 + [self setBackgroundImageForState:state withURLRequest:request placeholderImage:placeholderImage success:nil failure:nil];
208 +}
209 +
210 +- (void)setBackgroundImageForState:(UIControlState)state
211 + withURLRequest:(NSURLRequest *)urlRequest
212 + placeholderImage:(nullable UIImage *)placeholderImage
213 + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success
214 + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure
215 +{
216 + if ([self isActiveBackgroundTaskURLEqualToURLRequest:urlRequest forState:state]) {
217 + return;
218 + }
219 +
220 + [self cancelBackgroundImageDownloadTaskForState:state];
221 +
222 + AFImageDownloader *downloader = [[self class] sharedImageDownloader];
223 + id <AFImageRequestCache> imageCache = downloader.imageCache;
224 +
225 + //Use the image from the image cache if it exists
226 + UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil];
227 + if (cachedImage) {
228 + if (success) {
229 + success(urlRequest, nil, cachedImage);
230 + } else {
231 + [self setBackgroundImage:cachedImage forState:state];
232 + }
233 + [self af_setBackgroundImageDownloadReceipt:nil forState:state];
234 + } else {
235 + if (placeholderImage) {
236 + [self setBackgroundImage:placeholderImage forState:state];
237 + }
238 +
239 + __weak __typeof(self)weakSelf = self;
240 + NSUUID *downloadID = [NSUUID UUID];
241 + AFImageDownloadReceipt *receipt;
242 + receipt = [downloader
243 + downloadImageForURLRequest:urlRequest
244 + withReceiptID:downloadID
245 + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) {
246 + __strong __typeof(weakSelf)strongSelf = weakSelf;
247 + if ([[strongSelf af_backgroundImageDownloadReceiptForState:state].receiptID isEqual:downloadID]) {
248 + if (success) {
249 + success(request, response, responseObject);
250 + } else if(responseObject) {
251 + [strongSelf setBackgroundImage:responseObject forState:state];
252 + }
253 + [strongSelf af_setBackgroundImageDownloadReceipt:nil forState:state];
254 + }
255 +
256 + }
257 + failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {
258 + __strong __typeof(weakSelf)strongSelf = weakSelf;
259 + if ([[strongSelf af_backgroundImageDownloadReceiptForState:state].receiptID isEqual:downloadID]) {
260 + if (failure) {
261 + failure(request, response, error);
262 + }
263 + [strongSelf af_setBackgroundImageDownloadReceipt:nil forState:state];
264 + }
265 + }];
266 +
267 + [self af_setBackgroundImageDownloadReceipt:receipt forState:state];
268 + }
269 +}
270 +
271 +#pragma mark -
272 +
273 +- (void)cancelImageDownloadTaskForState:(UIControlState)state {
274 + AFImageDownloadReceipt *receipt = [self af_imageDownloadReceiptForState:state];
275 + if (receipt != nil) {
276 + [[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:receipt];
277 + [self af_setImageDownloadReceipt:nil forState:state];
278 + }
279 +}
280 +
281 +- (void)cancelBackgroundImageDownloadTaskForState:(UIControlState)state {
282 + AFImageDownloadReceipt *receipt = [self af_backgroundImageDownloadReceiptForState:state];
283 + if (receipt != nil) {
284 + [[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:receipt];
285 + [self af_setBackgroundImageDownloadReceipt:nil forState:state];
286 + }
287 +}
288 +
289 +- (BOOL)isActiveTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest forState:(UIControlState)state {
290 + AFImageDownloadReceipt *receipt = [self af_imageDownloadReceiptForState:state];
291 + return [receipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString];
292 +}
293 +
294 +- (BOOL)isActiveBackgroundTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest forState:(UIControlState)state {
295 + AFImageDownloadReceipt *receipt = [self af_backgroundImageDownloadReceiptForState:state];
296 + return [receipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString];
297 +}
298 +
299 +
300 +@end
301 +
302 +#endif
1 +//
2 +// UIImage+AFNetworking.h
3 +//
4 +//
5 +// Created by Paulo Ferreira on 08/07/15.
6 +//
7 +// Permission is hereby granted, free of charge, to any person obtaining a copy
8 +// of this software and associated documentation files (the "Software"), to deal
9 +// in the Software without restriction, including without limitation the rights
10 +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 +// copies of the Software, and to permit persons to whom the Software is
12 +// furnished to do so, subject to the following conditions:
13 +//
14 +// The above copyright notice and this permission notice shall be included in
15 +// all copies or substantial portions of the Software.
16 +//
17 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 +// THE SOFTWARE.
24 +
25 +#if TARGET_OS_IOS || TARGET_OS_TV
26 +
27 +#import <UIKit/UIKit.h>
28 +
29 +@interface UIImage (AFNetworking)
30 +
31 ++ (UIImage*) safeImageWithData:(NSData*)data;
32 +
33 +@end
34 +
35 +#endif
1 +// UIImageView+AFNetworking.h
2 +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 +//
4 +// Permission is hereby granted, free of charge, to any person obtaining a copy
5 +// of this software and associated documentation files (the "Software"), to deal
6 +// in the Software without restriction, including without limitation the rights
7 +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 +// copies of the Software, and to permit persons to whom the Software is
9 +// furnished to do so, subject to the following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included in
12 +// all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 +// THE SOFTWARE.
21 +
22 +#import <Foundation/Foundation.h>
23 +
24 +#import <TargetConditionals.h>
25 +
26 +#if TARGET_OS_IOS || TARGET_OS_TV
27 +
28 +#import <UIKit/UIKit.h>
29 +
30 +NS_ASSUME_NONNULL_BEGIN
31 +
32 +@class AFImageDownloader;
33 +
34 +/**
35 + 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.
36 + */
37 +@interface UIImageView (AFNetworking)
38 +
39 +///------------------------------------
40 +/// @name Accessing the Image Downloader
41 +///------------------------------------
42 +
43 +/**
44 + Set the shared image downloader used to download images.
45 +
46 + @param imageDownloader The shared image downloader used to download images.
47 + */
48 ++ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader;
49 +
50 +/**
51 + The shared image downloader used to download images.
52 + */
53 ++ (AFImageDownloader *)sharedImageDownloader;
54 +
55 +///--------------------
56 +/// @name Setting Image
57 +///--------------------
58 +
59 +/**
60 + 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.
61 +
62 + 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.
63 +
64 + 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:`
65 +
66 + @param url The URL used for the image request.
67 + */
68 +- (void)setImageWithURL:(NSURL *)url;
69 +
70 +/**
71 + 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.
72 +
73 + 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.
74 +
75 + 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:`
76 +
77 + @param url The URL used for the image request.
78 + @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.
79 + */
80 +- (void)setImageWithURL:(NSURL *)url
81 + placeholderImage:(nullable UIImage *)placeholderImage;
82 +
83 +/**
84 + 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.
85 +
86 + 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.
87 +
88 + 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.
89 +
90 + @param urlRequest The URL request used for the image request.
91 + @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.
92 + @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`.
93 + @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.
94 + */
95 +- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest
96 + placeholderImage:(nullable UIImage *)placeholderImage
97 + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success
98 + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure;
99 +
100 +/**
101 + Cancels any executing image operation for the receiver, if one exists.
102 + */
103 +- (void)cancelImageDownloadTask;
104 +
105 +@end
106 +
107 +NS_ASSUME_NONNULL_END
108 +
109 +#endif
1 +// UIImageView+AFNetworking.m
2 +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 +//
4 +// Permission is hereby granted, free of charge, to any person obtaining a copy
5 +// of this software and associated documentation files (the "Software"), to deal
6 +// in the Software without restriction, including without limitation the rights
7 +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 +// copies of the Software, and to permit persons to whom the Software is
9 +// furnished to do so, subject to the following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included in
12 +// all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 +// THE SOFTWARE.
21 +
22 +#import "UIImageView+AFNetworking.h"
23 +
24 +#import <objc/runtime.h>
25 +
26 +#if TARGET_OS_IOS || TARGET_OS_TV
27 +
28 +#import "AFImageDownloader.h"
29 +
30 +@interface UIImageView (_AFNetworking)
31 +@property (readwrite, nonatomic, strong, setter = af_setActiveImageDownloadReceipt:) AFImageDownloadReceipt *af_activeImageDownloadReceipt;
32 +@end
33 +
34 +@implementation UIImageView (_AFNetworking)
35 +
36 +- (AFImageDownloadReceipt *)af_activeImageDownloadReceipt {
37 + return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, @selector(af_activeImageDownloadReceipt));
38 +}
39 +
40 +- (void)af_setActiveImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt {
41 + objc_setAssociatedObject(self, @selector(af_activeImageDownloadReceipt), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
42 +}
43 +
44 +@end
45 +
46 +#pragma mark -
47 +
48 +@implementation UIImageView (AFNetworking)
49 +
50 ++ (AFImageDownloader *)sharedImageDownloader {
51 + return objc_getAssociatedObject(self, @selector(sharedImageDownloader)) ?: [AFImageDownloader defaultInstance];
52 +}
53 +
54 ++ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader {
55 + objc_setAssociatedObject(self, @selector(sharedImageDownloader), imageDownloader, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
56 +}
57 +
58 +#pragma mark -
59 +
60 +- (void)setImageWithURL:(NSURL *)url {
61 + [self setImageWithURL:url placeholderImage:nil];
62 +}
63 +
64 +- (void)setImageWithURL:(NSURL *)url
65 + placeholderImage:(UIImage *)placeholderImage
66 +{
67 + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
68 + [request addValue:@"image/*" forHTTPHeaderField:@"Accept"];
69 +
70 + [self setImageWithURLRequest:request placeholderImage:placeholderImage success:nil failure:nil];
71 +}
72 +
73 +- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest
74 + placeholderImage:(UIImage *)placeholderImage
75 + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success
76 + failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure
77 +{
78 +
79 + if ([urlRequest URL] == nil) {
80 + [self cancelImageDownloadTask];
81 + self.image = placeholderImage;
82 + return;
83 + }
84 +
85 + if ([self isActiveTaskURLEqualToURLRequest:urlRequest]){
86 + return;
87 + }
88 +
89 + [self cancelImageDownloadTask];
90 +
91 + AFImageDownloader *downloader = [[self class] sharedImageDownloader];
92 + id <AFImageRequestCache> imageCache = downloader.imageCache;
93 +
94 + //Use the image from the image cache if it exists
95 + UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil];
96 + if (cachedImage) {
97 + if (success) {
98 + success(urlRequest, nil, cachedImage);
99 + } else {
100 + self.image = cachedImage;
101 + }
102 + [self clearActiveDownloadInformation];
103 + } else {
104 + if (placeholderImage) {
105 + self.image = placeholderImage;
106 + }
107 +
108 + __weak __typeof(self)weakSelf = self;
109 + NSUUID *downloadID = [NSUUID UUID];
110 + AFImageDownloadReceipt *receipt;
111 + receipt = [downloader
112 + downloadImageForURLRequest:urlRequest
113 + withReceiptID:downloadID
114 + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) {
115 + __strong __typeof(weakSelf)strongSelf = weakSelf;
116 + if ([strongSelf.af_activeImageDownloadReceipt.receiptID isEqual:downloadID]) {
117 + if (success) {
118 + success(request, response, responseObject);
119 + } else if(responseObject) {
120 + strongSelf.image = responseObject;
121 + }
122 + [strongSelf clearActiveDownloadInformation];
123 + }
124 +
125 + }
126 + failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {
127 + __strong __typeof(weakSelf)strongSelf = weakSelf;
128 + if ([strongSelf.af_activeImageDownloadReceipt.receiptID isEqual:downloadID]) {
129 + if (failure) {
130 + failure(request, response, error);
131 + }
132 + [strongSelf clearActiveDownloadInformation];
133 + }
134 + }];
135 +
136 + self.af_activeImageDownloadReceipt = receipt;
137 + }
138 +}
139 +
140 +- (void)cancelImageDownloadTask {
141 + if (self.af_activeImageDownloadReceipt != nil) {
142 + [[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:self.af_activeImageDownloadReceipt];
143 + [self clearActiveDownloadInformation];
144 + }
145 +}
146 +
147 +- (void)clearActiveDownloadInformation {
148 + self.af_activeImageDownloadReceipt = nil;
149 +}
150 +
151 +- (BOOL)isActiveTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest {
152 + return [self.af_activeImageDownloadReceipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString];
153 +}
154 +
155 +@end
156 +
157 +#endif
1 +// UIKit+AFNetworking.h
2 +//
3 +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
4 +//
5 +// Permission is hereby granted, free of charge, to any person obtaining a copy
6 +// of this software and associated documentation files (the "Software"), to deal
7 +// in the Software without restriction, including without limitation the rights
8 +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 +// copies of the Software, and to permit persons to whom the Software is
10 +// furnished to do so, subject to the following conditions:
11 +//
12 +// The above copyright notice and this permission notice shall be included in
13 +// all copies or substantial portions of the Software.
14 +//
15 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 +// THE SOFTWARE.
22 +
23 +#if TARGET_OS_IOS || TARGET_OS_TV
24 +#import <UIKit/UIKit.h>
25 +
26 +#ifndef _UIKIT_AFNETWORKING_
27 + #define _UIKIT_AFNETWORKING_
28 +
29 +#if TARGET_OS_IOS
30 + #import "AFAutoPurgingImageCache.h"
31 + #import "AFImageDownloader.h"
32 + #import "AFNetworkActivityIndicatorManager.h"
33 + #import "UIRefreshControl+AFNetworking.h"
34 + #import "UIWebView+AFNetworking.h"
35 +#endif
36 +
37 + #import "UIActivityIndicatorView+AFNetworking.h"
38 + #import "UIButton+AFNetworking.h"
39 + #import "UIImageView+AFNetworking.h"
40 + #import "UIProgressView+AFNetworking.h"
41 +#endif /* _UIKIT_AFNETWORKING_ */
42 +#endif
1 +// UIProgressView+AFNetworking.h
2 +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 +//
4 +// Permission is hereby granted, free of charge, to any person obtaining a copy
5 +// of this software and associated documentation files (the "Software"), to deal
6 +// in the Software without restriction, including without limitation the rights
7 +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 +// copies of the Software, and to permit persons to whom the Software is
9 +// furnished to do so, subject to the following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included in
12 +// all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 +// THE SOFTWARE.
21 +
22 +#import <Foundation/Foundation.h>
23 +
24 +#import <TargetConditionals.h>
25 +
26 +#if TARGET_OS_IOS || TARGET_OS_TV
27 +
28 +#import <UIKit/UIKit.h>
29 +
30 +NS_ASSUME_NONNULL_BEGIN
31 +
32 +
33 +/**
34 + 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.
35 + */
36 +@interface UIProgressView (AFNetworking)
37 +
38 +///------------------------------------
39 +/// @name Setting Session Task Progress
40 +///------------------------------------
41 +
42 +/**
43 + Binds the progress to the upload progress of the specified session task.
44 +
45 + @param task The session task.
46 + @param animated `YES` if the change should be animated, `NO` if the change should happen immediately.
47 + */
48 +- (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task
49 + animated:(BOOL)animated;
50 +
51 +/**
52 + Binds the progress to the download progress of the specified session task.
53 +
54 + @param task The session task.
55 + @param animated `YES` if the change should be animated, `NO` if the change should happen immediately.
56 + */
57 +- (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task
58 + animated:(BOOL)animated;
59 +
60 +@end
61 +
62 +NS_ASSUME_NONNULL_END
63 +
64 +#endif
1 +// UIProgressView+AFNetworking.m
2 +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 +//
4 +// Permission is hereby granted, free of charge, to any person obtaining a copy
5 +// of this software and associated documentation files (the "Software"), to deal
6 +// in the Software without restriction, including without limitation the rights
7 +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 +// copies of the Software, and to permit persons to whom the Software is
9 +// furnished to do so, subject to the following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included in
12 +// all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 +// THE SOFTWARE.
21 +
22 +#import "UIProgressView+AFNetworking.h"
23 +
24 +#import <objc/runtime.h>
25 +
26 +#if TARGET_OS_IOS || TARGET_OS_TV
27 +
28 +#import "AFURLSessionManager.h"
29 +
30 +static void * AFTaskCountOfBytesSentContext = &AFTaskCountOfBytesSentContext;
31 +static void * AFTaskCountOfBytesReceivedContext = &AFTaskCountOfBytesReceivedContext;
32 +
33 +#pragma mark -
34 +
35 +@implementation UIProgressView (AFNetworking)
36 +
37 +- (BOOL)af_uploadProgressAnimated {
38 + return [(NSNumber *)objc_getAssociatedObject(self, @selector(af_uploadProgressAnimated)) boolValue];
39 +}
40 +
41 +- (void)af_setUploadProgressAnimated:(BOOL)animated {
42 + objc_setAssociatedObject(self, @selector(af_uploadProgressAnimated), @(animated), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
43 +}
44 +
45 +- (BOOL)af_downloadProgressAnimated {
46 + return [(NSNumber *)objc_getAssociatedObject(self, @selector(af_downloadProgressAnimated)) boolValue];
47 +}
48 +
49 +- (void)af_setDownloadProgressAnimated:(BOOL)animated {
50 + objc_setAssociatedObject(self, @selector(af_downloadProgressAnimated), @(animated), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
51 +}
52 +
53 +#pragma mark -
54 +
55 +- (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task
56 + animated:(BOOL)animated
57 +{
58 + if (task.state == NSURLSessionTaskStateCompleted) {
59 + return;
60 + }
61 +
62 + [task addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesSentContext];
63 + [task addObserver:self forKeyPath:@"countOfBytesSent" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesSentContext];
64 +
65 + [self af_setUploadProgressAnimated:animated];
66 +}
67 +
68 +- (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task
69 + animated:(BOOL)animated
70 +{
71 + if (task.state == NSURLSessionTaskStateCompleted) {
72 + return;
73 + }
74 +
75 + [task addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext];
76 + [task addObserver:self forKeyPath:@"countOfBytesReceived" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext];
77 +
78 + [self af_setDownloadProgressAnimated:animated];
79 +}
80 +
81 +#pragma mark - NSKeyValueObserving
82 +
83 +- (void)observeValueForKeyPath:(NSString *)keyPath
84 + ofObject:(id)object
85 + change:(__unused NSDictionary *)change
86 + context:(void *)context
87 +{
88 + if (context == AFTaskCountOfBytesSentContext || context == AFTaskCountOfBytesReceivedContext) {
89 + if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesSent))]) {
90 + if ([object countOfBytesExpectedToSend] > 0) {
91 + dispatch_async(dispatch_get_main_queue(), ^{
92 + [self setProgress:[object countOfBytesSent] / ([object countOfBytesExpectedToSend] * 1.0f) animated:self.af_uploadProgressAnimated];
93 + });
94 + }
95 + }
96 +
97 + if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesReceived))]) {
98 + if ([object countOfBytesExpectedToReceive] > 0) {
99 + dispatch_async(dispatch_get_main_queue(), ^{
100 + [self setProgress:[object countOfBytesReceived] / ([object countOfBytesExpectedToReceive] * 1.0f) animated:self.af_downloadProgressAnimated];
101 + });
102 + }
103 + }
104 +
105 + if ([keyPath isEqualToString:NSStringFromSelector(@selector(state))]) {
106 + if ([(NSURLSessionTask *)object state] == NSURLSessionTaskStateCompleted) {
107 + @try {
108 + [object removeObserver:self forKeyPath:NSStringFromSelector(@selector(state))];
109 +
110 + if (context == AFTaskCountOfBytesSentContext) {
111 + [object removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesSent))];
112 + }
113 +
114 + if (context == AFTaskCountOfBytesReceivedContext) {
115 + [object removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesReceived))];
116 + }
117 + }
118 + @catch (NSException * __unused exception) {}
119 + }
120 + }
121 + }
122 +}
123 +
124 +@end
125 +
126 +#endif
1 +// UIRefreshControl+AFNetworking.m
2 +//
3 +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
4 +//
5 +// Permission is hereby granted, free of charge, to any person obtaining a copy
6 +// of this software and associated documentation files (the "Software"), to deal
7 +// in the Software without restriction, including without limitation the rights
8 +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 +// copies of the Software, and to permit persons to whom the Software is
10 +// furnished to do so, subject to the following conditions:
11 +//
12 +// The above copyright notice and this permission notice shall be included in
13 +// all copies or substantial portions of the Software.
14 +//
15 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 +// THE SOFTWARE.
22 +
23 +#import <Foundation/Foundation.h>
24 +
25 +#import <TargetConditionals.h>
26 +
27 +#if TARGET_OS_IOS
28 +
29 +#import <UIKit/UIKit.h>
30 +
31 +NS_ASSUME_NONNULL_BEGIN
32 +
33 +/**
34 + 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.
35 + */
36 +@interface UIRefreshControl (AFNetworking)
37 +
38 +///-----------------------------------
39 +/// @name Refreshing for Session Tasks
40 +///-----------------------------------
41 +
42 +/**
43 + Binds the refreshing state to the state of the specified task.
44 +
45 + @param task The task. If `nil`, automatic updating from any previously specified operation will be disabled.
46 + */
47 +- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task;
48 +
49 +@end
50 +
51 +NS_ASSUME_NONNULL_END
52 +
53 +#endif
1 +// UIRefreshControl+AFNetworking.m
2 +//
3 +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
4 +//
5 +// Permission is hereby granted, free of charge, to any person obtaining a copy
6 +// of this software and associated documentation files (the "Software"), to deal
7 +// in the Software without restriction, including without limitation the rights
8 +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 +// copies of the Software, and to permit persons to whom the Software is
10 +// furnished to do so, subject to the following conditions:
11 +//
12 +// The above copyright notice and this permission notice shall be included in
13 +// all copies or substantial portions of the Software.
14 +//
15 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 +// THE SOFTWARE.
22 +
23 +#import "UIRefreshControl+AFNetworking.h"
24 +#import <objc/runtime.h>
25 +
26 +#if TARGET_OS_IOS
27 +
28 +#import "AFURLSessionManager.h"
29 +
30 +@interface AFRefreshControlNotificationObserver : NSObject
31 +@property (readonly, nonatomic, weak) UIRefreshControl *refreshControl;
32 +- (instancetype)initWithActivityRefreshControl:(UIRefreshControl *)refreshControl;
33 +
34 +- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task;
35 +
36 +@end
37 +
38 +@implementation UIRefreshControl (AFNetworking)
39 +
40 +- (AFRefreshControlNotificationObserver *)af_notificationObserver {
41 + AFRefreshControlNotificationObserver *notificationObserver = objc_getAssociatedObject(self, @selector(af_notificationObserver));
42 + if (notificationObserver == nil) {
43 + notificationObserver = [[AFRefreshControlNotificationObserver alloc] initWithActivityRefreshControl:self];
44 + objc_setAssociatedObject(self, @selector(af_notificationObserver), notificationObserver, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
45 + }
46 + return notificationObserver;
47 +}
48 +
49 +- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task {
50 + [[self af_notificationObserver] setRefreshingWithStateOfTask:task];
51 +}
52 +
53 +@end
54 +
55 +@implementation AFRefreshControlNotificationObserver
56 +
57 +- (instancetype)initWithActivityRefreshControl:(UIRefreshControl *)refreshControl
58 +{
59 + self = [super init];
60 + if (self) {
61 + _refreshControl = refreshControl;
62 + }
63 + return self;
64 +}
65 +
66 +- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task {
67 + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
68 +
69 + [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil];
70 + [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil];
71 + [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil];
72 +
73 + if (task) {
74 + UIRefreshControl *refreshControl = self.refreshControl;
75 + if (task.state == NSURLSessionTaskStateRunning) {
76 + [refreshControl beginRefreshing];
77 +
78 + [notificationCenter addObserver:self selector:@selector(af_beginRefreshing) name:AFNetworkingTaskDidResumeNotification object:task];
79 + [notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingTaskDidCompleteNotification object:task];
80 + [notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingTaskDidSuspendNotification object:task];
81 + } else {
82 + [refreshControl endRefreshing];
83 + }
84 + }
85 +}
86 +
87 +#pragma mark -
88 +
89 +- (void)af_beginRefreshing {
90 + dispatch_async(dispatch_get_main_queue(), ^{
91 + [self.refreshControl beginRefreshing];
92 + });
93 +}
94 +
95 +- (void)af_endRefreshing {
96 + dispatch_async(dispatch_get_main_queue(), ^{
97 + [self.refreshControl endRefreshing];
98 + });
99 +}
100 +
101 +#pragma mark -
102 +
103 +- (void)dealloc {
104 + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
105 +
106 + [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil];
107 + [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil];
108 + [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil];
109 +}
110 +
111 +@end
112 +
113 +#endif
1 +// UIWebView+AFNetworking.h
2 +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 +//
4 +// Permission is hereby granted, free of charge, to any person obtaining a copy
5 +// of this software and associated documentation files (the "Software"), to deal
6 +// in the Software without restriction, including without limitation the rights
7 +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 +// copies of the Software, and to permit persons to whom the Software is
9 +// furnished to do so, subject to the following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included in
12 +// all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 +// THE SOFTWARE.
21 +
22 +#import <Foundation/Foundation.h>
23 +
24 +#import <TargetConditionals.h>
25 +
26 +#if TARGET_OS_IOS
27 +
28 +#import <UIKit/UIKit.h>
29 +#import <WebKit/WebKit.h>
30 +
31 +NS_ASSUME_NONNULL_BEGIN
32 +
33 +@class AFHTTPSessionManager;
34 +
35 +/**
36 + 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.
37 +
38 + @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.
39 + */
40 +@interface WKWebView (AFNetworking)
41 +
42 +/**
43 + The session manager used to download all requests.
44 + */
45 +@property (nonatomic, strong) AFHTTPSessionManager *sessionManager;
46 +
47 +/**
48 + Asynchronously loads the specified request.
49 +
50 + @param request A URL request identifying the location of the content to load. This must not be `nil`.
51 + @param progress A progress object monitoring the current download progress.
52 + @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.
53 + @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.
54 + */
55 +- (void)loadRequest:(NSURLRequest *)request
56 + progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress
57 + success:(nullable NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success
58 + failure:(nullable void (^)(NSError *error))failure;
59 +
60 +/**
61 + Asynchronously loads the data associated with a particular request with a specified MIME type and text encoding.
62 +
63 + @param request A URL request identifying the location of the content to load. This must not be `nil`.
64 + @param MIMEType The MIME type of the content. Defaults to the content type of the response if not specified.
65 + @param textEncodingName The IANA encoding name, as in `utf-8` or `utf-16`. Defaults to the response text encoding if not specified.
66 +@param progress A progress object monitoring the current download progress.
67 + @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.
68 + @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.
69 + */
70 +- (void)loadRequest:(NSURLRequest *)request
71 + MIMEType:(nullable NSString *)MIMEType
72 + textEncodingName:(nullable NSString *)textEncodingName
73 + progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress
74 + success:(nullable NSData * (^)(NSHTTPURLResponse *response, NSData *data))success
75 + failure:(nullable void (^)(NSError *error))failure;
76 +
77 +@end
78 +
79 +NS_ASSUME_NONNULL_END
80 +
81 +#endif
1 +// UIWebView+AFNetworking.m
2 +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 +//
4 +// Permission is hereby granted, free of charge, to any person obtaining a copy
5 +// of this software and associated documentation files (the "Software"), to deal
6 +// in the Software without restriction, including without limitation the rights
7 +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 +// copies of the Software, and to permit persons to whom the Software is
9 +// furnished to do so, subject to the following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included in
12 +// all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 +// THE SOFTWARE.
21 +
22 +#import "UIWebView+AFNetworking.h"
23 +
24 +#import <objc/runtime.h>
25 +
26 +#if TARGET_OS_IOS
27 +
28 +#import "AFHTTPSessionManager.h"
29 +#import "AFURLResponseSerialization.h"
30 +#import "AFURLRequestSerialization.h"
31 +
32 +@interface WKWebView (_AFNetworking)
33 +@property (readwrite, nonatomic, strong, setter = af_setURLSessionTask:) NSURLSessionDataTask *af_URLSessionTask;
34 +@end
35 +
36 +@implementation WKWebView (_AFNetworking)
37 +
38 +- (NSURLSessionDataTask *)af_URLSessionTask {
39 + return (NSURLSessionDataTask *)objc_getAssociatedObject(self, @selector(af_URLSessionTask));
40 +}
41 +
42 +- (void)af_setURLSessionTask:(NSURLSessionDataTask *)af_URLSessionTask {
43 + objc_setAssociatedObject(self, @selector(af_URLSessionTask), af_URLSessionTask, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
44 +}
45 +
46 +@end
47 +
48 +#pragma mark -
49 +
50 +@implementation WKWebView (AFNetworking)
51 +
52 +- (AFHTTPSessionManager *)sessionManager {
53 + static AFHTTPSessionManager *_af_defaultHTTPSessionManager = nil;
54 + static dispatch_once_t onceToken;
55 + dispatch_once(&onceToken, ^{
56 + _af_defaultHTTPSessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
57 + _af_defaultHTTPSessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
58 + _af_defaultHTTPSessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
59 + });
60 +
61 + return objc_getAssociatedObject(self, @selector(sessionManager)) ?: _af_defaultHTTPSessionManager;
62 +}
63 +
64 +- (void)setSessionManager:(AFHTTPSessionManager *)sessionManager {
65 + objc_setAssociatedObject(self, @selector(sessionManager), sessionManager, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
66 +}
67 +
68 +- (AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer {
69 + static AFHTTPResponseSerializer <AFURLResponseSerialization> *_af_defaultResponseSerializer = nil;
70 + static dispatch_once_t onceToken;
71 + dispatch_once(&onceToken, ^{
72 + _af_defaultResponseSerializer = [AFHTTPResponseSerializer serializer];
73 + });
74 +
75 + return objc_getAssociatedObject(self, @selector(responseSerializer)) ?: _af_defaultResponseSerializer;
76 +}
77 +
78 +- (void)setResponseSerializer:(AFHTTPResponseSerializer<AFURLResponseSerialization> *)responseSerializer {
79 + objc_setAssociatedObject(self, @selector(responseSerializer), responseSerializer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
80 +}
81 +
82 +#pragma mark -
83 +
84 +- (void)loadRequest:(NSURLRequest *)request
85 + progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress
86 + success:(NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success
87 + failure:(void (^)(NSError *error))failure
88 +{
89 + [self loadRequest:request MIMEType:nil textEncodingName:nil progress:progress success:^NSData *(NSHTTPURLResponse *response, NSData *data) {
90 + NSStringEncoding stringEncoding = NSUTF8StringEncoding;
91 + if (response.textEncodingName) {
92 + CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)response.textEncodingName);
93 + if (encoding != kCFStringEncodingInvalidId) {
94 + stringEncoding = CFStringConvertEncodingToNSStringEncoding(encoding);
95 + }
96 + }
97 +
98 + NSString *string = [[NSString alloc] initWithData:data encoding:stringEncoding];
99 + if (success) {
100 + string = success(response, string);
101 + }
102 +
103 + return [string dataUsingEncoding:stringEncoding];
104 + } failure:failure];
105 +}
106 +
107 +- (void)loadRequest:(NSURLRequest *)request
108 + MIMEType:(NSString *)MIMEType
109 + textEncodingName:(NSString *)textEncodingName
110 + progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress
111 + success:(NSData * (^)(NSHTTPURLResponse *response, NSData *data))success
112 + failure:(void (^)(NSError *error))failure
113 +{
114 + NSParameterAssert(request);
115 +
116 + if (self.af_URLSessionTask.state == NSURLSessionTaskStateRunning || self.af_URLSessionTask.state == NSURLSessionTaskStateSuspended) {
117 + [self.af_URLSessionTask cancel];
118 + }
119 + self.af_URLSessionTask = nil;
120 +
121 + __weak __typeof(self)weakSelf = self;
122 + __block NSURLSessionDataTask *dataTask;
123 + dataTask = [self.sessionManager
124 + dataTaskWithRequest:request
125 + uploadProgress:nil
126 + downloadProgress:nil
127 + completionHandler:^(NSURLResponse * _Nonnull response, id _Nonnull responseObject, NSError * _Nullable error) {
128 + __strong __typeof(weakSelf) strongSelf = weakSelf;
129 + if (error) {
130 + if (failure) {
131 + failure(error);
132 + }
133 + } else {
134 + if (success) {
135 + success((NSHTTPURLResponse *)response, responseObject);
136 + }
137 + [strongSelf loadData:responseObject MIMEType:MIMEType characterEncodingName:textEncodingName baseURL:[dataTask.currentRequest URL]];
138 +
139 + if ([strongSelf.UIDelegate respondsToSelector:@selector(webViewDidFinishLoad:)]) {
140 + [strongSelf.UIDelegate webViewDidClose:strongSelf];
141 + }
142 + }
143 + }];
144 + self.af_URLSessionTask = dataTask;
145 + if (progress != nil) {
146 + *progress = [self.sessionManager downloadProgressForTask:dataTask];
147 + }
148 + [self.af_URLSessionTask resume];
149 +
150 + if ([self.UIDelegate respondsToSelector:@selector(webViewDidStartLoad:)]) {
151 + //[self.UIDelegate webViewDidStartLoad:self];
152 + }
153 +}
154 +
155 +@end
156 +
157 +#endif
1 +#import "FMDatabase.h"
2 +#import "FMResultSet.h"
3 +#import "FMDatabaseAdditions.h"
4 +#import "FMDatabaseQueue.h"
5 +#import "FMDatabasePool.h"
1 +#import <Foundation/Foundation.h>
2 +#import "sqlite3.h"
3 +#import "FMResultSet.h"
4 +#import "FMDatabasePool.h"
5 +
6 +
7 +#if ! __has_feature(objc_arc)
8 + #define FMDBAutorelease(__v) ([__v autorelease]);
9 + #define FMDBReturnAutoreleased FMDBAutorelease
10 +
11 + #define FMDBRetain(__v) ([__v retain]);
12 + #define FMDBReturnRetained FMDBRetain
13 +
14 + #define FMDBRelease(__v) ([__v release]);
15 +
16 + #define FMDBDispatchQueueRelease(__v) (dispatch_release(__v));
17 +#else
18 + // -fobjc-arc
19 + #define FMDBAutorelease(__v)
20 + #define FMDBReturnAutoreleased(__v) (__v)
21 +
22 + #define FMDBRetain(__v)
23 + #define FMDBReturnRetained(__v) (__v)
24 +
25 + #define FMDBRelease(__v)
26 +
27 +// If OS_OBJECT_USE_OBJC=1, then the dispatch objects will be treated like ObjC objects
28 +// and will participate in ARC.
29 +// See the section on "Dispatch Queues and Automatic Reference Counting" in "Grand Central Dispatch (GCD) Reference" for details.
30 + #if OS_OBJECT_USE_OBJC
31 + #define FMDBDispatchQueueRelease(__v)
32 + #else
33 + #define FMDBDispatchQueueRelease(__v) (dispatch_release(__v));
34 + #endif
35 +#endif
36 +
37 +#if !__has_feature(objc_instancetype)
38 + #define instancetype id
39 +#endif
40 +
41 +
42 +typedef int(^FMDBExecuteStatementsCallbackBlock)(NSDictionary *resultsDictionary);
43 +
44 +
45 +/** A SQLite ([http://sqlite.org/](http://sqlite.org/)) Objective-C wrapper.
46 +
47 + ### Usage
48 + The three main classes in FMDB are:
49 +
50 + - `FMDatabase` - Represents a single SQLite database. Used for executing SQL statements.
51 + - `<FMResultSet>` - Represents the results of executing a query on an `FMDatabase`.
52 + - `<FMDatabaseQueue>` - If you want to perform queries and updates on multiple threads, you'll want to use this class.
53 +
54 + ### See also
55 +
56 + - `<FMDatabasePool>` - A pool of `FMDatabase` objects.
57 + - `<FMStatement>` - A wrapper for `sqlite_stmt`.
58 +
59 + ### External links
60 +
61 + - [FMDB on GitHub](https://github.com/ccgus/fmdb) including introductory documentation
62 + - [SQLite web site](http://sqlite.org/)
63 + - [FMDB mailing list](http://groups.google.com/group/fmdb)
64 + - [SQLite FAQ](http://www.sqlite.org/faq.html)
65 +
66 + @warning Do not instantiate a single `FMDatabase` object and use it across multiple threads. Instead, use `<FMDatabaseQueue>`.
67 +
68 + */
69 +
70 +#pragma clang diagnostic push
71 +#pragma clang diagnostic ignored "-Wobjc-interface-ivars"
72 +
73 +
74 +@interface FMDatabase : NSObject {
75 +
76 + sqlite3* _db;
77 + NSString* _databasePath;
78 + BOOL _logsErrors;
79 + BOOL _crashOnErrors;
80 + BOOL _traceExecution;
81 + BOOL _checkedOut;
82 + BOOL _shouldCacheStatements;
83 + BOOL _isExecutingStatement;
84 + BOOL _inTransaction;
85 + NSTimeInterval _maxBusyRetryTimeInterval;
86 + NSTimeInterval _startBusyRetryTime;
87 +
88 + NSMutableDictionary *_cachedStatements;
89 + NSMutableSet *_openResultSets;
90 + NSMutableSet *_openFunctions;
91 +
92 + NSDateFormatter *_dateFormat;
93 +}
94 +
95 +///-----------------
96 +/// @name Properties
97 +///-----------------
98 +
99 +/** Whether should trace execution */
100 +
101 +@property (atomic, assign) BOOL traceExecution;
102 +
103 +/** Whether checked out or not */
104 +
105 +@property (atomic, assign) BOOL checkedOut;
106 +
107 +/** Crash on errors */
108 +
109 +@property (atomic, assign) BOOL crashOnErrors;
110 +
111 +/** Logs errors */
112 +
113 +@property (atomic, assign) BOOL logsErrors;
114 +
115 +/** Dictionary of cached statements */
116 +
117 +@property (atomic, retain) NSMutableDictionary *cachedStatements;
118 +
119 +///---------------------
120 +/// @name Initialization
121 +///---------------------
122 +
123 +/** Create a `FMDatabase` object.
124 +
125 + An `FMDatabase` is created with a path to a SQLite database file. This path can be one of these three:
126 +
127 + 1. A file system path. The file does not have to exist on disk. If it does not exist, it is created for you.
128 + 2. An empty string (`@""`). An empty database is created at a temporary location. This database is deleted with the `FMDatabase` connection is closed.
129 + 3. `nil`. An in-memory database is created. This database will be destroyed with the `FMDatabase` connection is closed.
130 +
131 + For example, to create/open a database in your Mac OS X `tmp` folder:
132 +
133 + FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"];
134 +
135 + Or, in iOS, you might open a database in the app's `Documents` directory:
136 +
137 + NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
138 + NSString *dbPath = [docsPath stringByAppendingPathComponent:@"test.db"];
139 + FMDatabase *db = [FMDatabase databaseWithPath:dbPath];
140 +
141 + (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))
142 +
143 + @param inPath Path of database file
144 +
145 + @return `FMDatabase` object if successful; `nil` if failure.
146 +
147 + */
148 +
149 ++ (instancetype)databaseWithPath:(NSString*)inPath;
150 +
151 +/** Initialize a `FMDatabase` object.
152 +
153 + An `FMDatabase` is created with a path to a SQLite database file. This path can be one of these three:
154 +
155 + 1. A file system path. The file does not have to exist on disk. If it does not exist, it is created for you.
156 + 2. An empty string (`@""`). An empty database is created at a temporary location. This database is deleted with the `FMDatabase` connection is closed.
157 + 3. `nil`. An in-memory database is created. This database will be destroyed with the `FMDatabase` connection is closed.
158 +
159 + For example, to create/open a database in your Mac OS X `tmp` folder:
160 +
161 + FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"];
162 +
163 + Or, in iOS, you might open a database in the app's `Documents` directory:
164 +
165 + NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
166 + NSString *dbPath = [docsPath stringByAppendingPathComponent:@"test.db"];
167 + FMDatabase *db = [FMDatabase databaseWithPath:dbPath];
168 +
169 + (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))
170 +
171 + @param inPath Path of database file
172 +
173 + @return `FMDatabase` object if successful; `nil` if failure.
174 +
175 + */
176 +
177 +- (instancetype)initWithPath:(NSString*)inPath;
178 +
179 +
180 +///-----------------------------------
181 +/// @name Opening and closing database
182 +///-----------------------------------
183 +
184 +/** Opening a new database connection
185 +
186 + The database is opened for reading and writing, and is created if it does not already exist.
187 +
188 + @return `YES` if successful, `NO` on error.
189 +
190 + @see [sqlite3_open()](http://sqlite.org/c3ref/open.html)
191 + @see openWithFlags:
192 + @see close
193 + */
194 +
195 +- (BOOL)open;
196 +
197 +/** Opening a new database connection with flags
198 +
199 + @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:
200 +
201 + `SQLITE_OPEN_READONLY`
202 +
203 + The database is opened in read-only mode. If the database does not already exist, an error is returned.
204 +
205 + `SQLITE_OPEN_READWRITE`
206 +
207 + 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.
208 +
209 + `SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE`
210 +
211 + 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.
212 +
213 + @return `YES` if successful, `NO` on error.
214 +
215 + @see [sqlite3_open_v2()](http://sqlite.org/c3ref/open.html)
216 + @see open
217 + @see close
218 + */
219 +
220 +#if SQLITE_VERSION_NUMBER >= 3005000
221 +- (BOOL)openWithFlags:(int)flags;
222 +#endif
223 +
224 +/** Closing a database connection
225 +
226 + @return `YES` if success, `NO` on error.
227 +
228 + @see [sqlite3_close()](http://sqlite.org/c3ref/close.html)
229 + @see open
230 + @see openWithFlags:
231 + */
232 +
233 +- (BOOL)close;
234 +
235 +/** Test to see if we have a good connection to the database.
236 +
237 + This will confirm whether:
238 +
239 + - is database open
240 + - if open, it will try a simple SELECT statement and confirm that it succeeds.
241 +
242 + @return `YES` if everything succeeds, `NO` on failure.
243 + */
244 +
245 +- (BOOL)goodConnection;
246 +
247 +
248 +///----------------------
249 +/// @name Perform updates
250 +///----------------------
251 +
252 +/** Execute single update statement
253 +
254 + 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.
255 +
256 + 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.
257 +
258 + @param sql The SQL to be performed, with optional `?` placeholders.
259 +
260 + @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.
261 +
262 + @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.).
263 +
264 + @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
265 +
266 + @see lastError
267 + @see lastErrorCode
268 + @see lastErrorMessage
269 + @see [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html)
270 + */
271 +
272 +- (BOOL)executeUpdate:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ...;
273 +
274 +/** Execute single update statement
275 +
276 + @see executeUpdate:withErrorAndBindings:
277 +
278 + @warning **Deprecated**: Please use `<executeUpdate:withErrorAndBindings>` instead.
279 + */
280 +
281 +- (BOOL)update:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ... __attribute__ ((deprecated));
282 +
283 +/** Execute single update statement
284 +
285 + 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.
286 +
287 + 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.
288 +
289 + @param sql The SQL to be performed, with optional `?` placeholders.
290 +
291 + @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.).
292 +
293 + @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
294 +
295 + @see lastError
296 + @see lastErrorCode
297 + @see lastErrorMessage
298 + @see [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html)
299 +
300 + @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.
301 +
302 + @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:>`.
303 + */
304 +
305 +- (BOOL)executeUpdate:(NSString*)sql, ...;
306 +
307 +/** Execute single update statement
308 +
309 + 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.
310 +
311 + @param format The SQL to be performed, with `printf`-style escape sequences.
312 +
313 + @param ... Optional parameters to bind to use in conjunction with the `printf`-style escape sequences in the SQL statement.
314 +
315 + @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
316 +
317 + @see executeUpdate:
318 + @see lastError
319 + @see lastErrorCode
320 + @see lastErrorMessage
321 +
322 + @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
323 +
324 + [db executeUpdateWithFormat:@"INSERT INTO test (name) VALUES (%@)", @"Gus"];
325 +
326 + is actually replacing the `%@` with `?` placeholder, and then performing something equivalent to `<executeUpdate:>`
327 +
328 + [db executeUpdate:@"INSERT INTO test (name) VALUES (?)", @"Gus"];
329 +
330 + 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 (%@)`.
331 + */
332 +
333 +- (BOOL)executeUpdateWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2);
334 +
335 +/** Execute single update statement
336 +
337 + 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.
338 +
339 + 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.
340 +
341 + @param sql The SQL to be performed, with optional `?` placeholders.
342 +
343 + @param arguments A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement.
344 +
345 + @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
346 +
347 + @see lastError
348 + @see lastErrorCode
349 + @see lastErrorMessage
350 + */
351 +
352 +- (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments;
353 +
354 +/** Execute single update statement
355 +
356 + 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.
357 +
358 + 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.
359 +
360 + @param sql The SQL to be performed, with optional `?` placeholders.
361 +
362 + @param arguments A `NSDictionary` of objects keyed by column names that will be used when binding values to the `?` placeholders in the SQL statement.
363 +
364 + @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
365 +
366 + @see lastError
367 + @see lastErrorCode
368 + @see lastErrorMessage
369 +*/
370 +
371 +- (BOOL)executeUpdate:(NSString*)sql withParameterDictionary:(NSDictionary *)arguments;
372 +
373 +
374 +/** Execute single update statement
375 +
376 + 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.
377 +
378 + 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.
379 +
380 + @param sql The SQL to be performed, with optional `?` placeholders.
381 +
382 + @param args A `va_list` of arguments.
383 +
384 + @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
385 +
386 + @see lastError
387 + @see lastErrorCode
388 + @see lastErrorMessage
389 + */
390 +
391 +- (BOOL)executeUpdate:(NSString*)sql withVAList: (va_list)args;
392 +
393 +/** Execute multiple SQL statements
394 +
395 + 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`.
396 +
397 + @param sql The SQL to be performed
398 +
399 + @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
400 +
401 + @see executeStatements:withResultBlock:
402 + @see [sqlite3_exec()](http://sqlite.org/c3ref/exec.html)
403 +
404 + */
405 +
406 +- (BOOL)executeStatements:(NSString *)sql;
407 +
408 +/** Execute multiple SQL statements with callback handler
409 +
410 + 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`.
411 +
412 + @param sql The SQL to be performed.
413 + @param block A block that will be called for any result sets returned by any SQL statements.
414 + Note, if you supply this block, it must return integer value, zero upon success (this would be a good opportunity to use SQLITE_OK),
415 + 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.
416 + This may be `nil` if you don't care to receive any results.
417 +
418 + @return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`,
419 + `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
420 +
421 + @see executeStatements:
422 + @see [sqlite3_exec()](http://sqlite.org/c3ref/exec.html)
423 +
424 + */
425 +
426 +- (BOOL)executeStatements:(NSString *)sql withResultBlock:(FMDBExecuteStatementsCallbackBlock)block;
427 +
428 +/** Last insert rowid
429 +
430 + 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.
431 +
432 + 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.
433 +
434 + @return The rowid of the last inserted row.
435 +
436 + @see [sqlite3_last_insert_rowid()](http://sqlite.org/c3ref/last_insert_rowid.html)
437 +
438 + */
439 +
440 +- (sqlite_int64)lastInsertRowId;
441 +
442 +/** The number of rows changed by prior SQL statement.
443 +
444 + 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.
445 +
446 + @return The number of rows changed by prior SQL statement.
447 +
448 + @see [sqlite3_changes()](http://sqlite.org/c3ref/changes.html)
449 +
450 + */
451 +
452 +- (int)changes;
453 +
454 +
455 +///-------------------------
456 +/// @name Retrieving results
457 +///-------------------------
458 +
459 +/** Execute select statement
460 +
461 + 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.
462 +
463 + 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.
464 +
465 + 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.
466 +
467 + @param sql The SELECT statement to be performed, with optional `?` placeholders.
468 +
469 + @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.).
470 +
471 + @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.
472 +
473 + @see FMResultSet
474 + @see [`FMResultSet next`](<[FMResultSet next]>)
475 + @see [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html)
476 +
477 + @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:>`.
478 + */
479 +
480 +- (FMResultSet *)executeQuery:(NSString*)sql, ...;
481 +
482 +/** Execute select statement
483 +
484 + 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.
485 +
486 + 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.
487 +
488 + @param format The SQL to be performed, with `printf`-style escape sequences.
489 +
490 + @param ... Optional parameters to bind to use in conjunction with the `printf`-style escape sequences in the SQL statement.
491 +
492 + @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.
493 +
494 + @see executeQuery:
495 + @see FMResultSet
496 + @see [`FMResultSet next`](<[FMResultSet next]>)
497 +
498 + @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
499 +
500 + [db executeQueryWithFormat:@"SELECT * FROM test WHERE name=%@", @"Gus"];
501 +
502 + is actually replacing the `%@` with `?` placeholder, and then performing something equivalent to `<executeQuery:>`
503 +
504 + [db executeQuery:@"SELECT * FROM test WHERE name=?", @"Gus"];
505 +
506 + 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=%@`.
507 +
508 + */
509 +
510 +- (FMResultSet *)executeQueryWithFormat:(NSString*)format, ... NS_FORMAT_FUNCTION(1,2);
511 +
512 +/** Execute select statement
513 +
514 + 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.
515 +
516 + 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.
517 +
518 + @param sql The SELECT statement to be performed, with optional `?` placeholders.
519 +
520 + @param arguments A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement.
521 +
522 + @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.
523 +
524 + @see FMResultSet
525 + @see [`FMResultSet next`](<[FMResultSet next]>)
526 + */
527 +
528 +- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments;
529 +
530 +/** Execute select statement
531 +
532 + 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.
533 +
534 + 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.
535 +
536 + @param sql The SELECT statement to be performed, with optional `?` placeholders.
537 +
538 + @param arguments A `NSDictionary` of objects keyed by column names that will be used when binding values to the `?` placeholders in the SQL statement.
539 +
540 + @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.
541 +
542 + @see FMResultSet
543 + @see [`FMResultSet next`](<[FMResultSet next]>)
544 + */
545 +
546 +- (FMResultSet *)executeQuery:(NSString *)sql withParameterDictionary:(NSDictionary *)arguments;
547 +
548 +
549 +// Documentation forthcoming.
550 +- (FMResultSet *)executeQuery:(NSString*)sql withVAList: (va_list)args;
551 +
552 +///-------------------
553 +/// @name Transactions
554 +///-------------------
555 +
556 +/** Begin a transaction
557 +
558 + @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
559 +
560 + @see commit
561 + @see rollback
562 + @see beginDeferredTransaction
563 + @see inTransaction
564 + */
565 +
566 +- (BOOL)beginTransaction;
567 +
568 +/** Begin a deferred transaction
569 +
570 + @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
571 +
572 + @see commit
573 + @see rollback
574 + @see beginTransaction
575 + @see inTransaction
576 + */
577 +
578 +- (BOOL)beginDeferredTransaction;
579 +
580 +/** Commit a transaction
581 +
582 + Commit a transaction that was initiated with either `<beginTransaction>` or with `<beginDeferredTransaction>`.
583 +
584 + @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
585 +
586 + @see beginTransaction
587 + @see beginDeferredTransaction
588 + @see rollback
589 + @see inTransaction
590 + */
591 +
592 +- (BOOL)commit;
593 +
594 +/** Rollback a transaction
595 +
596 + Rollback a transaction that was initiated with either `<beginTransaction>` or with `<beginDeferredTransaction>`.
597 +
598 + @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
599 +
600 + @see beginTransaction
601 + @see beginDeferredTransaction
602 + @see commit
603 + @see inTransaction
604 + */
605 +
606 +- (BOOL)rollback;
607 +
608 +/** Identify whether currently in a transaction or not
609 +
610 + @return `YES` if currently within transaction; `NO` if not.
611 +
612 + @see beginTransaction
613 + @see beginDeferredTransaction
614 + @see commit
615 + @see rollback
616 + */
617 +
618 +- (BOOL)inTransaction;
619 +
620 +
621 +///----------------------------------------
622 +/// @name Cached statements and result sets
623 +///----------------------------------------
624 +
625 +/** Clear cached statements */
626 +
627 +- (void)clearCachedStatements;
628 +
629 +/** Close all open result sets */
630 +
631 +- (void)closeOpenResultSets;
632 +
633 +/** Whether database has any open result sets
634 +
635 + @return `YES` if there are open result sets; `NO` if not.
636 + */
637 +
638 +- (BOOL)hasOpenResultSets;
639 +
640 +/** Return whether should cache statements or not
641 +
642 + @return `YES` if should cache statements; `NO` if not.
643 + */
644 +
645 +- (BOOL)shouldCacheStatements;
646 +
647 +/** Set whether should cache statements or not
648 +
649 + @param value `YES` if should cache statements; `NO` if not.
650 + */
651 +
652 +- (void)setShouldCacheStatements:(BOOL)value;
653 +
654 +
655 +///-------------------------
656 +/// @name Encryption methods
657 +///-------------------------
658 +
659 +/** Set encryption key.
660 +
661 + @param key The key to be used.
662 +
663 + @return `YES` if success, `NO` on error.
664 +
665 + @see http://www.sqlite-encrypt.com/develop-guide.htm
666 +
667 + @warning You need to have purchased the sqlite encryption extensions for this method to work.
668 + */
669 +
670 +- (BOOL)setKey:(NSString*)key;
671 +
672 +/** Reset encryption key
673 +
674 + @param key The key to be used.
675 +
676 + @return `YES` if success, `NO` on error.
677 +
678 + @see http://www.sqlite-encrypt.com/develop-guide.htm
679 +
680 + @warning You need to have purchased the sqlite encryption extensions for this method to work.
681 + */
682 +
683 +- (BOOL)rekey:(NSString*)key;
684 +
685 +/** Set encryption key using `keyData`.
686 +
687 + @param keyData The `NSData` to be used.
688 +
689 + @return `YES` if success, `NO` on error.
690 +
691 + @see http://www.sqlite-encrypt.com/develop-guide.htm
692 +
693 + @warning You need to have purchased the sqlite encryption extensions for this method to work.
694 + */
695 +
696 +- (BOOL)setKeyWithData:(NSData *)keyData;
697 +
698 +/** Reset encryption key using `keyData`.
699 +
700 + @param keyData The `NSData` to be used.
701 +
702 + @return `YES` if success, `NO` on error.
703 +
704 + @see http://www.sqlite-encrypt.com/develop-guide.htm
705 +
706 + @warning You need to have purchased the sqlite encryption extensions for this method to work.
707 + */
708 +
709 +- (BOOL)rekeyWithData:(NSData *)keyData;
710 +
711 +
712 +///------------------------------
713 +/// @name General inquiry methods
714 +///------------------------------
715 +
716 +/** The path of the database file
717 +
718 + @return path of database.
719 +
720 + */
721 +
722 +- (NSString *)databasePath;
723 +
724 +/** The underlying SQLite handle
725 +
726 + @return The `sqlite3` pointer.
727 +
728 + */
729 +
730 +- (sqlite3*)sqliteHandle;
731 +
732 +
733 +///-----------------------------
734 +/// @name Retrieving error codes
735 +///-----------------------------
736 +
737 +/** Last error message
738 +
739 + 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.
740 +
741 + @return `NSString` of the last error message.
742 +
743 + @see [sqlite3_errmsg()](http://sqlite.org/c3ref/errcode.html)
744 + @see lastErrorCode
745 + @see lastError
746 +
747 + */
748 +
749 +- (NSString*)lastErrorMessage;
750 +
751 +/** Last error code
752 +
753 + 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.
754 +
755 + @return Integer value of the last error code.
756 +
757 + @see [sqlite3_errcode()](http://sqlite.org/c3ref/errcode.html)
758 + @see lastErrorMessage
759 + @see lastError
760 +
761 + */
762 +
763 +- (int)lastErrorCode;
764 +
765 +/** Had error
766 +
767 + @return `YES` if there was an error, `NO` if no error.
768 +
769 + @see lastError
770 + @see lastErrorCode
771 + @see lastErrorMessage
772 +
773 + */
774 +
775 +- (BOOL)hadError;
776 +
777 +/** Last error
778 +
779 + @return `NSError` representing the last error.
780 +
781 + @see lastErrorCode
782 + @see lastErrorMessage
783 +
784 + */
785 +
786 +- (NSError*)lastError;
787 +
788 +
789 +// description forthcoming
790 +- (void)setMaxBusyRetryTimeInterval:(NSTimeInterval)timeoutInSeconds;
791 +- (NSTimeInterval)maxBusyRetryTimeInterval;
792 +
793 +
794 +#if SQLITE_VERSION_NUMBER >= 3007000
795 +
796 +///------------------
797 +/// @name Save points
798 +///------------------
799 +
800 +/** Start save point
801 +
802 + @param name Name of save point.
803 +
804 + @param outErr A `NSError` object to receive any error object (if any).
805 +
806 + @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
807 +
808 + @see releaseSavePointWithName:error:
809 + @see rollbackToSavePointWithName:error:
810 + */
811 +
812 +- (BOOL)startSavePointWithName:(NSString*)name error:(NSError**)outErr;
813 +
814 +/** Release save point
815 +
816 + @param name Name of save point.
817 +
818 + @param outErr A `NSError` object to receive any error object (if any).
819 +
820 + @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
821 +
822 + @see startSavePointWithName:error:
823 + @see rollbackToSavePointWithName:error:
824 +
825 + */
826 +
827 +- (BOOL)releaseSavePointWithName:(NSString*)name error:(NSError**)outErr;
828 +
829 +/** Roll back to save point
830 +
831 + @param name Name of save point.
832 + @param outErr A `NSError` object to receive any error object (if any).
833 +
834 + @return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
835 +
836 + @see startSavePointWithName:error:
837 + @see releaseSavePointWithName:error:
838 +
839 + */
840 +
841 +- (BOOL)rollbackToSavePointWithName:(NSString*)name error:(NSError**)outErr;
842 +
843 +/** Start save point
844 +
845 + @param block Block of code to perform from within save point.
846 +
847 + @return The NSError corresponding to the error, if any. If no error, returns `nil`.
848 +
849 + @see startSavePointWithName:error:
850 + @see releaseSavePointWithName:error:
851 + @see rollbackToSavePointWithName:error:
852 +
853 + */
854 +
855 +- (NSError*)inSavePoint:(void (^)(BOOL *rollback))block;
856 +
857 +#endif
858 +
859 +///----------------------------
860 +/// @name SQLite library status
861 +///----------------------------
862 +
863 +/** Test to see if the library is threadsafe
864 +
865 + @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.
866 +
867 + @see [sqlite3_threadsafe()](http://sqlite.org/c3ref/threadsafe.html)
868 + */
869 +
870 ++ (BOOL)isSQLiteThreadSafe;
871 +
872 +/** Run-time library version numbers
873 +
874 + @return The sqlite library version string.
875 +
876 + @see [sqlite3_libversion()](http://sqlite.org/c3ref/libversion.html)
877 + */
878 +
879 ++ (NSString*)sqliteLibVersion;
880 +
881 +
882 ++ (NSString*)FMDBUserVersion;
883 +
884 ++ (SInt32)FMDBVersion;
885 +
886 +
887 +///------------------------
888 +/// @name Make SQL function
889 +///------------------------
890 +
891 +/** Adds SQL functions or aggregates or to redefine the behavior of existing SQL functions or aggregates.
892 +
893 + For example:
894 +
895 + [queue inDatabase:^(FMDatabase *adb) {
896 +
897 + [adb executeUpdate:@"create table ftest (foo text)"];
898 + [adb executeUpdate:@"insert into ftest values ('hello')"];
899 + [adb executeUpdate:@"insert into ftest values ('hi')"];
900 + [adb executeUpdate:@"insert into ftest values ('not h!')"];
901 + [adb executeUpdate:@"insert into ftest values ('definitely not h!')"];
902 +
903 + [adb makeFunctionNamed:@"StringStartsWithH" maximumArguments:1 withBlock:^(sqlite3_context *context, int aargc, sqlite3_value **aargv) {
904 + if (sqlite3_value_type(aargv[0]) == SQLITE_TEXT) {
905 + @autoreleasepool {
906 + const char *c = (const char *)sqlite3_value_text(aargv[0]);
907 + NSString *s = [NSString stringWithUTF8String:c];
908 + sqlite3_result_int(context, [s hasPrefix:@"h"]);
909 + }
910 + }
911 + else {
912 + NSLog(@"Unknown formart for StringStartsWithH (%d) %s:%d", sqlite3_value_type(aargv[0]), __FUNCTION__, __LINE__);
913 + sqlite3_result_null(context);
914 + }
915 + }];
916 +
917 + int rowCount = 0;
918 + FMResultSet *ars = [adb executeQuery:@"select * from ftest where StringStartsWithH(foo)"];
919 + while ([ars next]) {
920 + rowCount++;
921 + NSLog(@"Does %@ start with 'h'?", [rs stringForColumnIndex:0]);
922 + }
923 + FMDBQuickCheck(rowCount == 2);
924 + }];
925 +
926 + @param name Name of function
927 +
928 + @param count Maximum number of parameters
929 +
930 + @param block The block of code for the function
931 +
932 + @see [sqlite3_create_function()](http://sqlite.org/c3ref/create_function.html)
933 + */
934 +
935 +- (void)makeFunctionNamed:(NSString*)name maximumArguments:(int)count withBlock:(void (^)(sqlite3_context *context, int argc, sqlite3_value **argv))block;
936 +
937 +
938 +///---------------------
939 +/// @name Date formatter
940 +///---------------------
941 +
942 +/** Generate an `NSDateFormatter` that won't be broken by permutations of timezones or locales.
943 +
944 + Use this method to generate values to set the dateFormat property.
945 +
946 + Example:
947 +
948 + myDB.dateFormat = [FMDatabase storeableDateFormat:@"yyyy-MM-dd HH:mm:ss"];
949 +
950 + @param format A valid NSDateFormatter format string.
951 +
952 + @return A `NSDateFormatter` that can be used for converting dates to strings and vice versa.
953 +
954 + @see hasDateFormatter
955 + @see setDateFormat:
956 + @see dateFromString:
957 + @see stringFromDate:
958 + @see storeableDateFormat:
959 +
960 + @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.
961 +
962 + */
963 +
964 ++ (NSDateFormatter *)storeableDateFormat:(NSString *)format;
965 +
966 +/** Test whether the database has a date formatter assigned.
967 +
968 + @return `YES` if there is a date formatter; `NO` if not.
969 +
970 + @see hasDateFormatter
971 + @see setDateFormat:
972 + @see dateFromString:
973 + @see stringFromDate:
974 + @see storeableDateFormat:
975 + */
976 +
977 +- (BOOL)hasDateFormatter;
978 +
979 +/** Set to a date formatter to use string dates with sqlite instead of the default UNIX timestamps.
980 +
981 + @param format Set to nil to use UNIX timestamps. Defaults to nil. Should be set using a formatter generated using FMDatabase::storeableDateFormat.
982 +
983 + @see hasDateFormatter
984 + @see setDateFormat:
985 + @see dateFromString:
986 + @see stringFromDate:
987 + @see storeableDateFormat:
988 +
989 + @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.
990 + */
991 +
992 +- (void)setDateFormat:(NSDateFormatter *)format;
993 +
994 +/** Convert the supplied NSString to NSDate, using the current database formatter.
995 +
996 + @param s `NSString` to convert to `NSDate`.
997 +
998 + @return The `NSDate` object; or `nil` if no formatter is set.
999 +
1000 + @see hasDateFormatter
1001 + @see setDateFormat:
1002 + @see dateFromString:
1003 + @see stringFromDate:
1004 + @see storeableDateFormat:
1005 + */
1006 +
1007 +- (NSDate *)dateFromString:(NSString *)s;
1008 +
1009 +/** Convert the supplied NSDate to NSString, using the current database formatter.
1010 +
1011 + @param date `NSDate` of date to convert to `NSString`.
1012 +
1013 + @return The `NSString` representation of the date; `nil` if no formatter is set.
1014 +
1015 + @see hasDateFormatter
1016 + @see setDateFormat:
1017 + @see dateFromString:
1018 + @see stringFromDate:
1019 + @see storeableDateFormat:
1020 + */
1021 +
1022 +- (NSString *)stringFromDate:(NSDate *)date;
1023 +
1024 +@end
1025 +
1026 +
1027 +/** Objective-C wrapper for `sqlite3_stmt`
1028 +
1029 + 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.
1030 +
1031 + ### See also
1032 +
1033 + - `<FMDatabase>`
1034 + - `<FMResultSet>`
1035 + - [`sqlite3_stmt`](http://www.sqlite.org/c3ref/stmt.html)
1036 + */
1037 +
1038 +@interface FMStatement : NSObject {
1039 + sqlite3_stmt *_statement;
1040 + NSString *_query;
1041 + long _useCount;
1042 + BOOL _inUse;
1043 +}
1044 +
1045 +///-----------------
1046 +/// @name Properties
1047 +///-----------------
1048 +
1049 +/** Usage count */
1050 +
1051 +@property (atomic, assign) long useCount;
1052 +
1053 +/** SQL statement */
1054 +
1055 +@property (atomic, retain) NSString *query;
1056 +
1057 +/** SQLite sqlite3_stmt
1058 +
1059 + @see [`sqlite3_stmt`](http://www.sqlite.org/c3ref/stmt.html)
1060 + */
1061 +
1062 +@property (atomic, assign) sqlite3_stmt *statement;
1063 +
1064 +/** Indication of whether the statement is in use */
1065 +
1066 +@property (atomic, assign) BOOL inUse;
1067 +
1068 +///----------------------------
1069 +/// @name Closing and Resetting
1070 +///----------------------------
1071 +
1072 +/** Close statement */
1073 +
1074 +- (void)close;
1075 +
1076 +/** Reset statement */
1077 +
1078 +- (void)reset;
1079 +
1080 +@end
1081 +
1082 +#pragma clang diagnostic pop
1083 +
1 +#import "FMDatabase.h"
2 +#import "unistd.h"
3 +#import <objc/runtime.h>
4 +
5 +@interface FMDatabase ()
6 +
7 +- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args;
8 +- (BOOL)executeUpdate:(NSString*)sql error:(NSError**)outErr withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args;
9 +
10 +@end
11 +
12 +@implementation FMDatabase
13 +@synthesize cachedStatements=_cachedStatements;
14 +@synthesize logsErrors=_logsErrors;
15 +@synthesize crashOnErrors=_crashOnErrors;
16 +@synthesize checkedOut=_checkedOut;
17 +@synthesize traceExecution=_traceExecution;
18 +
19 +#pragma mark FMDatabase instantiation and deallocation
20 +
21 ++ (instancetype)databaseWithPath:(NSString*)aPath {
22 + return FMDBReturnAutoreleased([[self alloc] initWithPath:aPath]);
23 +}
24 +
25 +- (instancetype)init {
26 + return [self initWithPath:nil];
27 +}
28 +
29 +- (instancetype)initWithPath:(NSString*)aPath {
30 +
31 + assert(sqlite3_threadsafe()); // whoa there big boy- gotta make sure sqlite it happy with what we're going to do.
32 +
33 + self = [super init];
34 +
35 + if (self) {
36 + _databasePath = [aPath copy];
37 + _openResultSets = [[NSMutableSet alloc] init];
38 + _db = nil;
39 + _logsErrors = YES;
40 + _crashOnErrors = NO;
41 + _maxBusyRetryTimeInterval = 2;
42 + }
43 +
44 + return self;
45 +}
46 +
47 +- (void)finalize {
48 + [self close];
49 + [super finalize];
50 +}
51 +
52 +- (void)dealloc {
53 + [self close];
54 + FMDBRelease(_openResultSets);
55 + FMDBRelease(_cachedStatements);
56 + FMDBRelease(_dateFormat);
57 + FMDBRelease(_databasePath);
58 + FMDBRelease(_openFunctions);
59 +
60 +#if ! __has_feature(objc_arc)
61 + [super dealloc];
62 +#endif
63 +}
64 +
65 +- (NSString *)databasePath {
66 + return _databasePath;
67 +}
68 +
69 ++ (NSString*)FMDBUserVersion {
70 + return @"2.5";
71 +}
72 +
73 +// returns 0x0240 for version 2.4. This makes it super easy to do things like:
74 +// /* need to make sure to do X with FMDB version 2.4 or later */
75 +// if ([FMDatabase FMDBVersion] >= 0x0240) { … }
76 +
77 ++ (SInt32)FMDBVersion {
78 +
79 + // we go through these hoops so that we only have to change the version number in a single spot.
80 + static dispatch_once_t once;
81 + static SInt32 FMDBVersionVal = 0;
82 +
83 + dispatch_once(&once, ^{
84 + NSString *prodVersion = [self FMDBUserVersion];
85 +
86 + if ([[prodVersion componentsSeparatedByString:@"."] count] < 3) {
87 + prodVersion = [prodVersion stringByAppendingString:@".0"];
88 + }
89 +
90 + NSString *junk = [prodVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
91 +
92 + char *e = nil;
93 + FMDBVersionVal = (int) strtoul([junk UTF8String], &e, 16);
94 +
95 + });
96 +
97 +
98 + return FMDBVersionVal;
99 +}
100 +
101 +#pragma mark SQLite information
102 +
103 ++ (NSString*)sqliteLibVersion {
104 + return [NSString stringWithFormat:@"%s", sqlite3_libversion()];
105 +}
106 +
107 ++ (BOOL)isSQLiteThreadSafe {
108 + // make sure to read the sqlite headers on this guy!
109 + return sqlite3_threadsafe() != 0;
110 +}
111 +
112 +- (sqlite3*)sqliteHandle {
113 + return _db;
114 +}
115 +
116 +- (const char*)sqlitePath {
117 +
118 + if (!_databasePath) {
119 + return ":memory:";
120 + }
121 +
122 + if ([_databasePath length] == 0) {
123 + return ""; // this creates a temporary database (it's an sqlite thing).
124 + }
125 +
126 + return [_databasePath fileSystemRepresentation];
127 +
128 +}
129 +
130 +#pragma mark Open and close database
131 +
132 +- (BOOL)open {
133 + if (_db) {
134 + return YES;
135 + }
136 +
137 + int err = sqlite3_open([self sqlitePath], &_db );
138 + if(err != SQLITE_OK) {
139 + NSLog(@"error opening!: %d", err);
140 + return NO;
141 + }
142 +
143 + if (_maxBusyRetryTimeInterval > 0.0) {
144 + // set the handler
145 + [self setMaxBusyRetryTimeInterval:_maxBusyRetryTimeInterval];
146 + }
147 +
148 +
149 + return YES;
150 +}
151 +
152 +#if SQLITE_VERSION_NUMBER >= 3005000
153 +- (BOOL)openWithFlags:(int)flags {
154 + if (_db) {
155 + return YES;
156 + }
157 +
158 + int err = sqlite3_open_v2([self sqlitePath], &_db, flags, NULL /* Name of VFS module to use */);
159 + if(err != SQLITE_OK) {
160 + NSLog(@"error opening!: %d", err);
161 + return NO;
162 + }
163 +
164 + if (_maxBusyRetryTimeInterval > 0.0) {
165 + // set the handler
166 + [self setMaxBusyRetryTimeInterval:_maxBusyRetryTimeInterval];
167 + }
168 +
169 + return YES;
170 +}
171 +#endif
172 +
173 +
174 +- (BOOL)close {
175 +
176 + [self clearCachedStatements];
177 + [self closeOpenResultSets];
178 +
179 + if (!_db) {
180 + return YES;
181 + }
182 +
183 + int rc;
184 + BOOL retry;
185 + BOOL triedFinalizingOpenStatements = NO;
186 +
187 + do {
188 + retry = NO;
189 + rc = sqlite3_close(_db);
190 + if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) {
191 + if (!triedFinalizingOpenStatements) {
192 + triedFinalizingOpenStatements = YES;
193 + sqlite3_stmt *pStmt;
194 + while ((pStmt = sqlite3_next_stmt(_db, nil)) !=0) {
195 + NSLog(@"Closing leaked statement");
196 + sqlite3_finalize(pStmt);
197 + retry = YES;
198 + }
199 + }
200 + }
201 + else if (SQLITE_OK != rc) {
202 + NSLog(@"error closing!: %d", rc);
203 + }
204 + }
205 + while (retry);
206 +
207 + _db = nil;
208 + return YES;
209 +}
210 +
211 +#pragma mark Busy handler routines
212 +
213 +// NOTE: appledoc seems to choke on this function for some reason;
214 +// so when generating documentation, you might want to ignore the
215 +// .m files so that it only documents the public interfaces outlined
216 +// in the .h files.
217 +//
218 +// This is a known appledoc bug that it has problems with C functions
219 +// within a class implementation, but for some reason, only this
220 +// C function causes problems; the rest don't. Anyway, ignoring the .m
221 +// files with appledoc will prevent this problem from occurring.
222 +
223 +static int FMDBDatabaseBusyHandler(void *f, int count) {
224 + FMDatabase *self = (__bridge FMDatabase*)f;
225 +
226 + if (count == 0) {
227 + self->_startBusyRetryTime = [NSDate timeIntervalSinceReferenceDate];
228 + return 1;
229 + }
230 +
231 + NSTimeInterval delta = [NSDate timeIntervalSinceReferenceDate] - (self->_startBusyRetryTime);
232 +
233 + if (delta < [self maxBusyRetryTimeInterval]) {
234 + int requestedSleepInMillseconds = (int) arc4random_uniform(50) + 50;
235 + int actualSleepInMilliseconds = sqlite3_sleep(requestedSleepInMillseconds);
236 + if (actualSleepInMilliseconds != requestedSleepInMillseconds) {
237 + NSLog(@"WARNING: Requested sleep of %i milliseconds, but SQLite returned %i. Maybe SQLite wasn't built with HAVE_USLEEP=1?", requestedSleepInMillseconds, actualSleepInMilliseconds);
238 + }
239 + return 1;
240 + }
241 +
242 + return 0;
243 +}
244 +
245 +- (void)setMaxBusyRetryTimeInterval:(NSTimeInterval)timeout {
246 +
247 + _maxBusyRetryTimeInterval = timeout;
248 +
249 + if (!_db) {
250 + return;
251 + }
252 +
253 + if (timeout > 0) {
254 + sqlite3_busy_handler(_db, &FMDBDatabaseBusyHandler, (__bridge void *)(self));
255 + }
256 + else {
257 + // turn it off otherwise
258 + sqlite3_busy_handler(_db, nil, nil);
259 + }
260 +}
261 +
262 +- (NSTimeInterval)maxBusyRetryTimeInterval {
263 + return _maxBusyRetryTimeInterval;
264 +}
265 +
266 +
267 +// we no longer make busyRetryTimeout public
268 +// but for folks who don't bother noticing that the interface to FMDatabase changed,
269 +// we'll still implement the method so they don't get suprise crashes
270 +- (int)busyRetryTimeout {
271 + NSLog(@"%s:%d", __FUNCTION__, __LINE__);
272 + NSLog(@"FMDB: busyRetryTimeout no longer works, please use maxBusyRetryTimeInterval");
273 + return -1;
274 +}
275 +
276 +- (void)setBusyRetryTimeout:(int)i {
277 + NSLog(@"%s:%d", __FUNCTION__, __LINE__);
278 + NSLog(@"FMDB: setBusyRetryTimeout does nothing, please use setMaxBusyRetryTimeInterval:");
279 +}
280 +
281 +#pragma mark Result set functions
282 +
283 +- (BOOL)hasOpenResultSets {
284 + return [_openResultSets count] > 0;
285 +}
286 +
287 +- (void)closeOpenResultSets {
288 +
289 + //Copy the set so we don't get mutation errors
290 + NSSet *openSetCopy = FMDBReturnAutoreleased([_openResultSets copy]);
291 + for (NSValue *rsInWrappedInATastyValueMeal in openSetCopy) {
292 + FMResultSet *rs = (FMResultSet *)[rsInWrappedInATastyValueMeal pointerValue];
293 +
294 + [rs setParentDB:nil];
295 + [rs close];
296 +
297 + [_openResultSets removeObject:rsInWrappedInATastyValueMeal];
298 + }
299 +}
300 +
301 +- (void)resultSetDidClose:(FMResultSet *)resultSet {
302 + NSValue *setValue = [NSValue valueWithNonretainedObject:resultSet];
303 +
304 + [_openResultSets removeObject:setValue];
305 +}
306 +
307 +#pragma mark Cached statements
308 +
309 +- (void)clearCachedStatements {
310 +
311 + for (NSMutableSet *statements in [_cachedStatements objectEnumerator]) {
312 + [statements makeObjectsPerformSelector:@selector(close)];
313 + }
314 +
315 + [_cachedStatements removeAllObjects];
316 +}
317 +
318 +- (FMStatement*)cachedStatementForQuery:(NSString*)query {
319 +
320 + NSMutableSet* statements = [_cachedStatements objectForKey:query];
321 +
322 + return [[statements objectsPassingTest:^BOOL(FMStatement* statement, BOOL *stop) {
323 +
324 + *stop = ![statement inUse];
325 + return *stop;
326 +
327 + }] anyObject];
328 +}
329 +
330 +
331 +- (void)setCachedStatement:(FMStatement*)statement forQuery:(NSString*)query {
332 +
333 + query = [query copy]; // in case we got handed in a mutable string...
334 + [statement setQuery:query];
335 +
336 + NSMutableSet* statements = [_cachedStatements objectForKey:query];
337 + if (!statements) {
338 + statements = [NSMutableSet set];
339 + }
340 +
341 + [statements addObject:statement];
342 +
343 + [_cachedStatements setObject:statements forKey:query];
344 +
345 + FMDBRelease(query);
346 +}
347 +
348 +#pragma mark Key routines
349 +
350 +- (BOOL)rekey:(NSString*)key {
351 + NSData *keyData = [NSData dataWithBytes:(void *)[key UTF8String] length:(NSUInteger)strlen([key UTF8String])];
352 +
353 + return [self rekeyWithData:keyData];
354 +}
355 +
356 +- (BOOL)rekeyWithData:(NSData *)keyData {
357 +#ifdef SQLITE_HAS_CODEC
358 + if (!keyData) {
359 + return NO;
360 + }
361 +
362 + int rc = sqlite3_rekey(_db, [keyData bytes], (int)[keyData length]);
363 +
364 + if (rc != SQLITE_OK) {
365 + NSLog(@"error on rekey: %d", rc);
366 + NSLog(@"%@", [self lastErrorMessage]);
367 + }
368 +
369 + return (rc == SQLITE_OK);
370 +#else
371 + return NO;
372 +#endif
373 +}
374 +
375 +- (BOOL)setKey:(NSString*)key {
376 + NSData *keyData = [NSData dataWithBytes:[key UTF8String] length:(NSUInteger)strlen([key UTF8String])];
377 +
378 + return [self setKeyWithData:keyData];
379 +}
380 +
381 +- (BOOL)setKeyWithData:(NSData *)keyData {
382 +#ifdef SQLITE_HAS_CODEC
383 + if (!keyData) {
384 + return NO;
385 + }
386 +
387 + int rc = sqlite3_key(_db, [keyData bytes], (int)[keyData length]);
388 +
389 + return (rc == SQLITE_OK);
390 +#else
391 + return NO;
392 +#endif
393 +}
394 +
395 +#pragma mark Date routines
396 +
397 ++ (NSDateFormatter *)storeableDateFormat:(NSString *)format {
398 +
399 + NSDateFormatter *result = FMDBReturnAutoreleased([[NSDateFormatter alloc] init]);
400 + result.dateFormat = format;
401 + result.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
402 + result.locale = FMDBReturnAutoreleased([[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]);
403 + return result;
404 +}
405 +
406 +
407 +- (BOOL)hasDateFormatter {
408 + return _dateFormat != nil;
409 +}
410 +
411 +- (void)setDateFormat:(NSDateFormatter *)format {
412 + FMDBAutorelease(_dateFormat);
413 + _dateFormat = FMDBReturnRetained(format);
414 +}
415 +
416 +- (NSDate *)dateFromString:(NSString *)s {
417 + return [_dateFormat dateFromString:s];
418 +}
419 +
420 +- (NSString *)stringFromDate:(NSDate *)date {
421 + return [_dateFormat stringFromDate:date];
422 +}
423 +
424 +#pragma mark State of database
425 +
426 +- (BOOL)goodConnection {
427 +
428 + if (!_db) {
429 + return NO;
430 + }
431 +
432 + FMResultSet *rs = [self executeQuery:@"select name from sqlite_master where type='table'"];
433 +
434 + if (rs) {
435 + [rs close];
436 + return YES;
437 + }
438 +
439 + return NO;
440 +}
441 +
442 +- (void)warnInUse {
443 + NSLog(@"The FMDatabase %@ is currently in use.", self);
444 +
445 +#ifndef NS_BLOCK_ASSERTIONS
446 + if (_crashOnErrors) {
447 + NSAssert(false, @"The FMDatabase %@ is currently in use.", self);
448 + abort();
449 + }
450 +#endif
451 +}
452 +
453 +- (BOOL)databaseExists {
454 +
455 + if (!_db) {
456 +
457 + NSLog(@"The FMDatabase %@ is not open.", self);
458 +
459 + #ifndef NS_BLOCK_ASSERTIONS
460 + if (_crashOnErrors) {
461 + NSAssert(false, @"The FMDatabase %@ is not open.", self);
462 + abort();
463 + }
464 + #endif
465 +
466 + return NO;
467 + }
468 +
469 + return YES;
470 +}
471 +
472 +#pragma mark Error routines
473 +
474 +- (NSString*)lastErrorMessage {
475 + return [NSString stringWithUTF8String:sqlite3_errmsg(_db)];
476 +}
477 +
478 +- (BOOL)hadError {
479 + int lastErrCode = [self lastErrorCode];
480 +
481 + return (lastErrCode > SQLITE_OK && lastErrCode < SQLITE_ROW);
482 +}
483 +
484 +- (int)lastErrorCode {
485 + return sqlite3_errcode(_db);
486 +}
487 +
488 +- (NSError*)errorWithMessage:(NSString*)message {
489 + NSDictionary* errorMessage = [NSDictionary dictionaryWithObject:message forKey:NSLocalizedDescriptionKey];
490 +
491 + return [NSError errorWithDomain:@"FMDatabase" code:sqlite3_errcode(_db) userInfo:errorMessage];
492 +}
493 +
494 +- (NSError*)lastError {
495 + return [self errorWithMessage:[self lastErrorMessage]];
496 +}
497 +
498 +#pragma mark Update information routines
499 +
500 +- (sqlite_int64)lastInsertRowId {
501 +
502 + if (_isExecutingStatement) {
503 + [self warnInUse];
504 + return NO;
505 + }
506 +
507 + _isExecutingStatement = YES;
508 +
509 + sqlite_int64 ret = sqlite3_last_insert_rowid(_db);
510 +
511 + _isExecutingStatement = NO;
512 +
513 + return ret;
514 +}
515 +
516 +- (int)changes {
517 + if (_isExecutingStatement) {
518 + [self warnInUse];
519 + return 0;
520 + }
521 +
522 + _isExecutingStatement = YES;
523 +
524 + int ret = sqlite3_changes(_db);
525 +
526 + _isExecutingStatement = NO;
527 +
528 + return ret;
529 +}
530 +
531 +#pragma mark SQL manipulation
532 +
533 +- (void)bindObject:(id)obj toColumn:(int)idx inStatement:(sqlite3_stmt*)pStmt {
534 +
535 + if ((!obj) || ((NSNull *)obj == [NSNull null])) {
536 + sqlite3_bind_null(pStmt, idx);
537 + }
538 +
539 + // FIXME - someday check the return codes on these binds.
540 + else if ([obj isKindOfClass:[NSData class]]) {
541 + const void *bytes = [obj bytes];
542 + if (!bytes) {
543 + // it's an empty NSData object, aka [NSData data].
544 + // Don't pass a NULL pointer, or sqlite will bind a SQL null instead of a blob.
545 + bytes = "";
546 + }
547 + sqlite3_bind_blob(pStmt, idx, bytes, (int)[obj length], SQLITE_STATIC);
548 + }
549 + else if ([obj isKindOfClass:[NSDate class]]) {
550 + if (self.hasDateFormatter)
551 + sqlite3_bind_text(pStmt, idx, [[self stringFromDate:obj] UTF8String], -1, SQLITE_STATIC);
552 + else
553 + sqlite3_bind_double(pStmt, idx, [obj timeIntervalSince1970]);
554 + }
555 + else if ([obj isKindOfClass:[NSNumber class]]) {
556 +
557 + if (strcmp([obj objCType], @encode(char)) == 0) {
558 + sqlite3_bind_int(pStmt, idx, [obj charValue]);
559 + }
560 + else if (strcmp([obj objCType], @encode(unsigned char)) == 0) {
561 + sqlite3_bind_int(pStmt, idx, [obj unsignedCharValue]);
562 + }
563 + else if (strcmp([obj objCType], @encode(short)) == 0) {
564 + sqlite3_bind_int(pStmt, idx, [obj shortValue]);
565 + }
566 + else if (strcmp([obj objCType], @encode(unsigned short)) == 0) {
567 + sqlite3_bind_int(pStmt, idx, [obj unsignedShortValue]);
568 + }
569 + else if (strcmp([obj objCType], @encode(int)) == 0) {
570 + sqlite3_bind_int(pStmt, idx, [obj intValue]);
571 + }
572 + else if (strcmp([obj objCType], @encode(unsigned int)) == 0) {
573 + sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedIntValue]);
574 + }
575 + else if (strcmp([obj objCType], @encode(long)) == 0) {
576 + sqlite3_bind_int64(pStmt, idx, [obj longValue]);
577 + }
578 + else if (strcmp([obj objCType], @encode(unsigned long)) == 0) {
579 + sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedLongValue]);
580 + }
581 + else if (strcmp([obj objCType], @encode(long long)) == 0) {
582 + sqlite3_bind_int64(pStmt, idx, [obj longLongValue]);
583 + }
584 + else if (strcmp([obj objCType], @encode(unsigned long long)) == 0) {
585 + sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedLongLongValue]);
586 + }
587 + else if (strcmp([obj objCType], @encode(float)) == 0) {
588 + sqlite3_bind_double(pStmt, idx, [obj floatValue]);
589 + }
590 + else if (strcmp([obj objCType], @encode(double)) == 0) {
591 + sqlite3_bind_double(pStmt, idx, [obj doubleValue]);
592 + }
593 + else if (strcmp([obj objCType], @encode(BOOL)) == 0) {
594 + sqlite3_bind_int(pStmt, idx, ([obj boolValue] ? 1 : 0));
595 + }
596 + else {
597 + sqlite3_bind_text(pStmt, idx, [[obj description] UTF8String], -1, SQLITE_STATIC);
598 + }
599 + }
600 + else {
601 + sqlite3_bind_text(pStmt, idx, [[obj description] UTF8String], -1, SQLITE_STATIC);
602 + }
603 +}
604 +
605 +- (void)extractSQL:(NSString *)sql argumentsList:(va_list)args intoString:(NSMutableString *)cleanedSQL arguments:(NSMutableArray *)arguments {
606 +
607 + NSUInteger length = [sql length];
608 + unichar last = '\0';
609 + for (NSUInteger i = 0; i < length; ++i) {
610 + id arg = nil;
611 + unichar current = [sql characterAtIndex:i];
612 + unichar add = current;
613 + if (last == '%') {
614 + switch (current) {
615 + case '@':
616 + arg = va_arg(args, id);
617 + break;
618 + case 'c':
619 + // warning: second argument to 'va_arg' is of promotable type 'char'; this va_arg has undefined behavior because arguments will be promoted to 'int'
620 + arg = [NSString stringWithFormat:@"%c", va_arg(args, int)];
621 + break;
622 + case 's':
623 + arg = [NSString stringWithUTF8String:va_arg(args, char*)];
624 + break;
625 + case 'd':
626 + case 'D':
627 + case 'i':
628 + arg = [NSNumber numberWithInt:va_arg(args, int)];
629 + break;
630 + case 'u':
631 + case 'U':
632 + arg = [NSNumber numberWithUnsignedInt:va_arg(args, unsigned int)];
633 + break;
634 + case 'h':
635 + i++;
636 + if (i < length && [sql characterAtIndex:i] == 'i') {
637 + // warning: second argument to 'va_arg' is of promotable type 'short'; this va_arg has undefined behavior because arguments will be promoted to 'int'
638 + arg = [NSNumber numberWithShort:(short)(va_arg(args, int))];
639 + }
640 + else if (i < length && [sql characterAtIndex:i] == 'u') {
641 + // 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'
642 + arg = [NSNumber numberWithUnsignedShort:(unsigned short)(va_arg(args, uint))];
643 + }
644 + else {
645 + i--;
646 + }
647 + break;
648 + case 'q':
649 + i++;
650 + if (i < length && [sql characterAtIndex:i] == 'i') {
651 + arg = [NSNumber numberWithLongLong:va_arg(args, long long)];
652 + }
653 + else if (i < length && [sql characterAtIndex:i] == 'u') {
654 + arg = [NSNumber numberWithUnsignedLongLong:va_arg(args, unsigned long long)];
655 + }
656 + else {
657 + i--;
658 + }
659 + break;
660 + case 'f':
661 + arg = [NSNumber numberWithDouble:va_arg(args, double)];
662 + break;
663 + case 'g':
664 + // warning: second argument to 'va_arg' is of promotable type 'float'; this va_arg has undefined behavior because arguments will be promoted to 'double'
665 + arg = [NSNumber numberWithFloat:(float)(va_arg(args, double))];
666 + break;
667 + case 'l':
668 + i++;
669 + if (i < length) {
670 + unichar next = [sql characterAtIndex:i];
671 + if (next == 'l') {
672 + i++;
673 + if (i < length && [sql characterAtIndex:i] == 'd') {
674 + //%lld
675 + arg = [NSNumber numberWithLongLong:va_arg(args, long long)];
676 + }
677 + else if (i < length && [sql characterAtIndex:i] == 'u') {
678 + //%llu
679 + arg = [NSNumber numberWithUnsignedLongLong:va_arg(args, unsigned long long)];
680 + }
681 + else {
682 + i--;
683 + }
684 + }
685 + else if (next == 'd') {
686 + //%ld
687 + arg = [NSNumber numberWithLong:va_arg(args, long)];
688 + }
689 + else if (next == 'u') {
690 + //%lu
691 + arg = [NSNumber numberWithUnsignedLong:va_arg(args, unsigned long)];
692 + }
693 + else {
694 + i--;
695 + }
696 + }
697 + else {
698 + i--;
699 + }
700 + break;
701 + default:
702 + // something else that we can't interpret. just pass it on through like normal
703 + break;
704 + }
705 + }
706 + else if (current == '%') {
707 + // percent sign; skip this character
708 + add = '\0';
709 + }
710 +
711 + if (arg != nil) {
712 + [cleanedSQL appendString:@"?"];
713 + [arguments addObject:arg];
714 + }
715 + else if (add == (unichar)'@' && last == (unichar) '%') {
716 + [cleanedSQL appendFormat:@"NULL"];
717 + }
718 + else if (add != '\0') {
719 + [cleanedSQL appendFormat:@"%C", add];
720 + }
721 + last = current;
722 + }
723 +}
724 +
725 +#pragma mark Execute queries
726 +
727 +- (FMResultSet *)executeQuery:(NSString *)sql withParameterDictionary:(NSDictionary *)arguments {
728 + return [self executeQuery:sql withArgumentsInArray:nil orDictionary:arguments orVAList:nil];
729 +}
730 +
731 +- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args {
732 +
733 + if (![self databaseExists]) {
734 + return 0x00;
735 + }
736 +
737 + if (_isExecutingStatement) {
738 + [self warnInUse];
739 + return 0x00;
740 + }
741 +
742 + _isExecutingStatement = YES;
743 +
744 + int rc = 0x00;
745 + sqlite3_stmt *pStmt = 0x00;
746 + FMStatement *statement = 0x00;
747 + FMResultSet *rs = 0x00;
748 +
749 + if (_traceExecution && sql) {
750 + NSLog(@"%@ executeQuery: %@", self, sql);
751 + }
752 +
753 + if (_shouldCacheStatements) {
754 + statement = [self cachedStatementForQuery:sql];
755 + pStmt = statement ? [statement statement] : 0x00;
756 + [statement reset];
757 + }
758 +
759 + if (!pStmt) {
760 +
761 + rc = sqlite3_prepare_v2(_db, [sql UTF8String], -1, &pStmt, 0);
762 +
763 + if (SQLITE_OK != rc) {
764 + if (_logsErrors) {
765 + NSLog(@"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
766 + NSLog(@"DB Query: %@", sql);
767 + NSLog(@"DB Path: %@", _databasePath);
768 + }
769 +
770 + if (_crashOnErrors) {
771 + NSAssert(false, @"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
772 + abort();
773 + }
774 +
775 + sqlite3_finalize(pStmt);
776 + _isExecutingStatement = NO;
777 + return nil;
778 + }
779 + }
780 +
781 + id obj;
782 + int idx = 0;
783 + int queryCount = sqlite3_bind_parameter_count(pStmt); // pointed out by Dominic Yu (thanks!)
784 +
785 + // If dictionaryArgs is passed in, that means we are using sqlite's named parameter support
786 + if (dictionaryArgs) {
787 +
788 + for (NSString *dictionaryKey in [dictionaryArgs allKeys]) {
789 +
790 + // Prefix the key with a colon.
791 + NSString *parameterName = [[NSString alloc] initWithFormat:@":%@", dictionaryKey];
792 +
793 + if (_traceExecution) {
794 + NSLog(@"%@ = %@", parameterName, [dictionaryArgs objectForKey:dictionaryKey]);
795 + }
796 +
797 + // Get the index for the parameter name.
798 + int namedIdx = sqlite3_bind_parameter_index(pStmt, [parameterName UTF8String]);
799 +
800 + FMDBRelease(parameterName);
801 +
802 + if (namedIdx > 0) {
803 + // Standard binding from here.
804 + [self bindObject:[dictionaryArgs objectForKey:dictionaryKey] toColumn:namedIdx inStatement:pStmt];
805 + // increment the binding count, so our check below works out
806 + idx++;
807 + }
808 + else {
809 + NSLog(@"Could not find index for %@", dictionaryKey);
810 + }
811 + }
812 + }
813 + else {
814 +
815 + while (idx < queryCount) {
816 +
817 + if (arrayArgs && idx < (int)[arrayArgs count]) {
818 + obj = [arrayArgs objectAtIndex:(NSUInteger)idx];
819 + }
820 + else if (args) {
821 + obj = va_arg(args, id);
822 + }
823 + else {
824 + //We ran out of arguments
825 + break;
826 + }
827 +
828 + if (_traceExecution) {
829 + if ([obj isKindOfClass:[NSData class]]) {
830 + NSLog(@"data: %ld bytes", (unsigned long)[(NSData*)obj length]);
831 + }
832 + else {
833 + NSLog(@"obj: %@", obj);
834 + }
835 + }
836 +
837 + idx++;
838 +
839 + [self bindObject:obj toColumn:idx inStatement:pStmt];
840 + }
841 + }
842 +
843 + if (idx != queryCount) {
844 + NSLog(@"Error: the bind count is not correct for the # of variables (executeQuery)");
845 + sqlite3_finalize(pStmt);
846 + _isExecutingStatement = NO;
847 + return nil;
848 + }
849 +
850 + FMDBRetain(statement); // to balance the release below
851 +
852 + if (!statement) {
853 + statement = [[FMStatement alloc] init];
854 + [statement setStatement:pStmt];
855 +
856 + if (_shouldCacheStatements && sql) {
857 + [self setCachedStatement:statement forQuery:sql];
858 + }
859 + }
860 +
861 + // the statement gets closed in rs's dealloc or [rs close];
862 + rs = [FMResultSet resultSetWithStatement:statement usingParentDatabase:self];
863 + [rs setQuery:sql];
864 +
865 + NSValue *openResultSet = [NSValue valueWithNonretainedObject:rs];
866 + [_openResultSets addObject:openResultSet];
867 +
868 + [statement setUseCount:[statement useCount] + 1];
869 +
870 + FMDBRelease(statement);
871 +
872 + _isExecutingStatement = NO;
873 +
874 + return rs;
875 +}
876 +
877 +- (FMResultSet *)executeQuery:(NSString*)sql, ... {
878 + va_list args;
879 + va_start(args, sql);
880 +
881 + id result = [self executeQuery:sql withArgumentsInArray:nil orDictionary:nil orVAList:args];
882 +
883 + va_end(args);
884 + return result;
885 +}
886 +
887 +- (FMResultSet *)executeQueryWithFormat:(NSString*)format, ... {
888 + va_list args;
889 + va_start(args, format);
890 +
891 + NSMutableString *sql = [NSMutableString stringWithCapacity:[format length]];
892 + NSMutableArray *arguments = [NSMutableArray array];
893 + [self extractSQL:format argumentsList:args intoString:sql arguments:arguments];
894 +
895 + va_end(args);
896 +
897 + return [self executeQuery:sql withArgumentsInArray:arguments];
898 +}
899 +
900 +- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments {
901 + return [self executeQuery:sql withArgumentsInArray:arguments orDictionary:nil orVAList:nil];
902 +}
903 +
904 +- (FMResultSet *)executeQuery:(NSString*)sql withVAList:(va_list)args {
905 + return [self executeQuery:sql withArgumentsInArray:nil orDictionary:nil orVAList:args];
906 +}
907 +
908 +#pragma mark Execute updates
909 +
910 +- (BOOL)executeUpdate:(NSString*)sql error:(NSError**)outErr withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args {
911 +
912 + if (![self databaseExists]) {
913 + return NO;
914 + }
915 +
916 + if (_isExecutingStatement) {
917 + [self warnInUse];
918 + return NO;
919 + }
920 +
921 + _isExecutingStatement = YES;
922 +
923 + int rc = 0x00;
924 + sqlite3_stmt *pStmt = 0x00;
925 + FMStatement *cachedStmt = 0x00;
926 +
927 + if (_traceExecution && sql) {
928 + NSLog(@"%@ executeUpdate: %@", self, sql);
929 + }
930 +
931 + if (_shouldCacheStatements) {
932 + cachedStmt = [self cachedStatementForQuery:sql];
933 + pStmt = cachedStmt ? [cachedStmt statement] : 0x00;
934 + [cachedStmt reset];
935 + }
936 +
937 + if (!pStmt) {
938 + rc = sqlite3_prepare_v2(_db, [sql UTF8String], -1, &pStmt, 0);
939 +
940 + if (SQLITE_OK != rc) {
941 + if (_logsErrors) {
942 + NSLog(@"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
943 + NSLog(@"DB Query: %@", sql);
944 + NSLog(@"DB Path: %@", _databasePath);
945 + }
946 +
947 + if (_crashOnErrors) {
948 + NSAssert(false, @"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
949 + abort();
950 + }
951 +
952 + sqlite3_finalize(pStmt);
953 +
954 + if (outErr) {
955 + *outErr = [self errorWithMessage:[NSString stringWithUTF8String:sqlite3_errmsg(_db)]];
956 + }
957 +
958 + _isExecutingStatement = NO;
959 + return NO;
960 + }
961 + }
962 +
963 + id obj;
964 + int idx = 0;
965 + int queryCount = sqlite3_bind_parameter_count(pStmt);
966 +
967 + // If dictionaryArgs is passed in, that means we are using sqlite's named parameter support
968 + if (dictionaryArgs) {
969 +
970 + for (NSString *dictionaryKey in [dictionaryArgs allKeys]) {
971 +
972 + // Prefix the key with a colon.
973 + NSString *parameterName = [[NSString alloc] initWithFormat:@":%@", dictionaryKey];
974 +
975 + if (_traceExecution) {
976 + NSLog(@"%@ = %@", parameterName, [dictionaryArgs objectForKey:dictionaryKey]);
977 + }
978 + // Get the index for the parameter name.
979 + int namedIdx = sqlite3_bind_parameter_index(pStmt, [parameterName UTF8String]);
980 +
981 + FMDBRelease(parameterName);
982 +
983 + if (namedIdx > 0) {
984 + // Standard binding from here.
985 + [self bindObject:[dictionaryArgs objectForKey:dictionaryKey] toColumn:namedIdx inStatement:pStmt];
986 +
987 + // increment the binding count, so our check below works out
988 + idx++;
989 + }
990 + else {
991 + NSLog(@"Could not find index for %@", dictionaryKey);
992 + }
993 + }
994 + }
995 + else {
996 +
997 + while (idx < queryCount) {
998 +
999 + if (arrayArgs && idx < (int)[arrayArgs count]) {
1000 + obj = [arrayArgs objectAtIndex:(NSUInteger)idx];
1001 + }
1002 + else if (args) {
1003 + obj = va_arg(args, id);
1004 + }
1005 + else {
1006 + //We ran out of arguments
1007 + break;
1008 + }
1009 +
1010 + if (_traceExecution) {
1011 + if ([obj isKindOfClass:[NSData class]]) {
1012 + NSLog(@"data: %ld bytes", (unsigned long)[(NSData*)obj length]);
1013 + }
1014 + else {
1015 + NSLog(@"obj: %@", obj);
1016 + }
1017 + }
1018 +
1019 + idx++;
1020 +
1021 + [self bindObject:obj toColumn:idx inStatement:pStmt];
1022 + }
1023 + }
1024 +
1025 +
1026 + if (idx != queryCount) {
1027 + NSLog(@"Error: the bind count (%d) is not correct for the # of variables in the query (%d) (%@) (executeUpdate)", idx, queryCount, sql);
1028 + sqlite3_finalize(pStmt);
1029 + _isExecutingStatement = NO;
1030 + return NO;
1031 + }
1032 +
1033 + /* Call sqlite3_step() to run the virtual machine. Since the SQL being
1034 + ** executed is not a SELECT statement, we assume no data will be returned.
1035 + */
1036 +
1037 + rc = sqlite3_step(pStmt);
1038 +
1039 + if (SQLITE_DONE == rc) {
1040 + // all is well, let's return.
1041 + }
1042 + else if (SQLITE_ERROR == rc) {
1043 + if (_logsErrors) {
1044 + NSLog(@"Error calling sqlite3_step (%d: %s) SQLITE_ERROR", rc, sqlite3_errmsg(_db));
1045 + NSLog(@"DB Query: %@", sql);
1046 + }
1047 + }
1048 + else if (SQLITE_MISUSE == rc) {
1049 + // uh oh.
1050 + if (_logsErrors) {
1051 + NSLog(@"Error calling sqlite3_step (%d: %s) SQLITE_MISUSE", rc, sqlite3_errmsg(_db));
1052 + NSLog(@"DB Query: %@", sql);
1053 + }
1054 + }
1055 + else {
1056 + // wtf?
1057 + if (_logsErrors) {
1058 + NSLog(@"Unknown error calling sqlite3_step (%d: %s) eu", rc, sqlite3_errmsg(_db));
1059 + NSLog(@"DB Query: %@", sql);
1060 + }
1061 + }
1062 +
1063 + if (rc == SQLITE_ROW) {
1064 + NSAssert(NO, @"A executeUpdate is being called with a query string '%@'", sql);
1065 + }
1066 +
1067 + if (_shouldCacheStatements && !cachedStmt) {
1068 + cachedStmt = [[FMStatement alloc] init];
1069 +
1070 + [cachedStmt setStatement:pStmt];
1071 +
1072 + [self setCachedStatement:cachedStmt forQuery:sql];
1073 +
1074 + FMDBRelease(cachedStmt);
1075 + }
1076 +
1077 + int closeErrorCode;
1078 +
1079 + if (cachedStmt) {
1080 + [cachedStmt setUseCount:[cachedStmt useCount] + 1];
1081 + closeErrorCode = sqlite3_reset(pStmt);
1082 + }
1083 + else {
1084 + /* Finalize the virtual machine. This releases all memory and other
1085 + ** resources allocated by the sqlite3_prepare() call above.
1086 + */
1087 + closeErrorCode = sqlite3_finalize(pStmt);
1088 + }
1089 +
1090 + if (closeErrorCode != SQLITE_OK) {
1091 + if (_logsErrors) {
1092 + NSLog(@"Unknown error finalizing or resetting statement (%d: %s)", closeErrorCode, sqlite3_errmsg(_db));
1093 + NSLog(@"DB Query: %@", sql);
1094 + }
1095 + }
1096 +
1097 + _isExecutingStatement = NO;
1098 + return (rc == SQLITE_DONE || rc == SQLITE_OK);
1099 +}
1100 +
1101 +
1102 +- (BOOL)executeUpdate:(NSString*)sql, ... {
1103 + va_list args;
1104 + va_start(args, sql);
1105 +
1106 + BOOL result = [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:nil orVAList:args];
1107 +
1108 + va_end(args);
1109 + return result;
1110 +}
1111 +
1112 +- (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments {
1113 + return [self executeUpdate:sql error:nil withArgumentsInArray:arguments orDictionary:nil orVAList:nil];
1114 +}
1115 +
1116 +- (BOOL)executeUpdate:(NSString*)sql withParameterDictionary:(NSDictionary *)arguments {
1117 + return [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:arguments orVAList:nil];
1118 +}
1119 +
1120 +- (BOOL)executeUpdate:(NSString*)sql withVAList:(va_list)args {
1121 + return [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:nil orVAList:args];
1122 +}
1123 +
1124 +- (BOOL)executeUpdateWithFormat:(NSString*)format, ... {
1125 + va_list args;
1126 + va_start(args, format);
1127 +
1128 + NSMutableString *sql = [NSMutableString stringWithCapacity:[format length]];
1129 + NSMutableArray *arguments = [NSMutableArray array];
1130 +
1131 + [self extractSQL:format argumentsList:args intoString:sql arguments:arguments];
1132 +
1133 + va_end(args);
1134 +
1135 + return [self executeUpdate:sql withArgumentsInArray:arguments];
1136 +}
1137 +
1138 +
1139 +int FMDBExecuteBulkSQLCallback(void *theBlockAsVoid, int columns, char **values, char **names); // shhh clang.
1140 +int FMDBExecuteBulkSQLCallback(void *theBlockAsVoid, int columns, char **values, char **names) {
1141 +
1142 + if (!theBlockAsVoid) {
1143 + return SQLITE_OK;
1144 + }
1145 +
1146 + int (^execCallbackBlock)(NSDictionary *resultsDictionary) = (__bridge int (^)(NSDictionary *__strong))(theBlockAsVoid);
1147 +
1148 + NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:(NSUInteger)columns];
1149 +
1150 + for (NSInteger i = 0; i < columns; i++) {
1151 + NSString *key = [NSString stringWithUTF8String:names[i]];
1152 + id value = values[i] ? [NSString stringWithUTF8String:values[i]] : [NSNull null];
1153 + [dictionary setObject:value forKey:key];
1154 + }
1155 +
1156 + return execCallbackBlock(dictionary);
1157 +}
1158 +
1159 +- (BOOL)executeStatements:(NSString *)sql {
1160 + return [self executeStatements:sql withResultBlock:nil];
1161 +}
1162 +
1163 +- (BOOL)executeStatements:(NSString *)sql withResultBlock:(FMDBExecuteStatementsCallbackBlock)block {
1164 +
1165 + int rc;
1166 + char *errmsg = nil;
1167 +
1168 + rc = sqlite3_exec([self sqliteHandle], [sql UTF8String], block ? FMDBExecuteBulkSQLCallback : nil, (__bridge void *)(block), &errmsg);
1169 +
1170 + if (errmsg && [self logsErrors]) {
1171 + NSLog(@"Error inserting batch: %s", errmsg);
1172 + sqlite3_free(errmsg);
1173 + }
1174 +
1175 + return (rc == SQLITE_OK);
1176 +}
1177 +
1178 +- (BOOL)executeUpdate:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ... {
1179 +
1180 + va_list args;
1181 + va_start(args, outErr);
1182 +
1183 + BOOL result = [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:args];
1184 +
1185 + va_end(args);
1186 + return result;
1187 +}
1188 +
1189 +
1190 +#pragma clang diagnostic push
1191 +#pragma clang diagnostic ignored "-Wdeprecated-implementations"
1192 +- (BOOL)update:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ... {
1193 + va_list args;
1194 + va_start(args, outErr);
1195 +
1196 + BOOL result = [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:args];
1197 +
1198 + va_end(args);
1199 + return result;
1200 +}
1201 +
1202 +#pragma clang diagnostic pop
1203 +
1204 +#pragma mark Transactions
1205 +
1206 +- (BOOL)rollback {
1207 + BOOL b = [self executeUpdate:@"rollback transaction"];
1208 +
1209 + if (b) {
1210 + _inTransaction = NO;
1211 + }
1212 +
1213 + return b;
1214 +}
1215 +
1216 +- (BOOL)commit {
1217 + BOOL b = [self executeUpdate:@"commit transaction"];
1218 +
1219 + if (b) {
1220 + _inTransaction = NO;
1221 + }
1222 +
1223 + return b;
1224 +}
1225 +
1226 +- (BOOL)beginDeferredTransaction {
1227 +
1228 + BOOL b = [self executeUpdate:@"begin deferred transaction"];
1229 + if (b) {
1230 + _inTransaction = YES;
1231 + }
1232 +
1233 + return b;
1234 +}
1235 +
1236 +- (BOOL)beginTransaction {
1237 +
1238 + BOOL b = [self executeUpdate:@"begin exclusive transaction"];
1239 + if (b) {
1240 + _inTransaction = YES;
1241 + }
1242 +
1243 + return b;
1244 +}
1245 +
1246 +- (BOOL)inTransaction {
1247 + return _inTransaction;
1248 +}
1249 +
1250 +#if SQLITE_VERSION_NUMBER >= 3007000
1251 +
1252 +static NSString *FMDBEscapeSavePointName(NSString *savepointName) {
1253 + return [savepointName stringByReplacingOccurrencesOfString:@"'" withString:@"''"];
1254 +}
1255 +
1256 +- (BOOL)startSavePointWithName:(NSString*)name error:(NSError**)outErr {
1257 +
1258 + NSParameterAssert(name);
1259 +
1260 + NSString *sql = [NSString stringWithFormat:@"savepoint '%@';", FMDBEscapeSavePointName(name)];
1261 +
1262 + if (![self executeUpdate:sql]) {
1263 +
1264 + if (outErr) {
1265 + *outErr = [self lastError];
1266 + }
1267 +
1268 + return NO;
1269 + }
1270 +
1271 + return YES;
1272 +}
1273 +
1274 +- (BOOL)releaseSavePointWithName:(NSString*)name error:(NSError**)outErr {
1275 +
1276 + NSParameterAssert(name);
1277 +
1278 + NSString *sql = [NSString stringWithFormat:@"release savepoint '%@';", FMDBEscapeSavePointName(name)];
1279 + BOOL worked = [self executeUpdate:sql];
1280 +
1281 + if (!worked && outErr) {
1282 + *outErr = [self lastError];
1283 + }
1284 +
1285 + return worked;
1286 +}
1287 +
1288 +- (BOOL)rollbackToSavePointWithName:(NSString*)name error:(NSError**)outErr {
1289 +
1290 + NSParameterAssert(name);
1291 +
1292 + NSString *sql = [NSString stringWithFormat:@"rollback transaction to savepoint '%@';", FMDBEscapeSavePointName(name)];
1293 + BOOL worked = [self executeUpdate:sql];
1294 +
1295 + if (!worked && outErr) {
1296 + *outErr = [self lastError];
1297 + }
1298 +
1299 + return worked;
1300 +}
1301 +
1302 +- (NSError*)inSavePoint:(void (^)(BOOL *rollback))block {
1303 + static unsigned long savePointIdx = 0;
1304 +
1305 + NSString *name = [NSString stringWithFormat:@"dbSavePoint%ld", savePointIdx++];
1306 +
1307 + BOOL shouldRollback = NO;
1308 +
1309 + NSError *err = 0x00;
1310 +
1311 + if (![self startSavePointWithName:name error:&err]) {
1312 + return err;
1313 + }
1314 +
1315 + block(&shouldRollback);
1316 +
1317 + if (shouldRollback) {
1318 + // We need to rollback and release this savepoint to remove it
1319 + [self rollbackToSavePointWithName:name error:&err];
1320 + }
1321 + [self releaseSavePointWithName:name error:&err];
1322 +
1323 + return err;
1324 +}
1325 +
1326 +#endif
1327 +
1328 +#pragma mark Cache statements
1329 +
1330 +- (BOOL)shouldCacheStatements {
1331 + return _shouldCacheStatements;
1332 +}
1333 +
1334 +- (void)setShouldCacheStatements:(BOOL)value {
1335 +
1336 + _shouldCacheStatements = value;
1337 +
1338 + if (_shouldCacheStatements && !_cachedStatements) {
1339 + [self setCachedStatements:[NSMutableDictionary dictionary]];
1340 + }
1341 +
1342 + if (!_shouldCacheStatements) {
1343 + [self setCachedStatements:nil];
1344 + }
1345 +}
1346 +
1347 +#pragma mark Callback function
1348 +
1349 +void FMDBBlockSQLiteCallBackFunction(sqlite3_context *context, int argc, sqlite3_value **argv); // -Wmissing-prototypes
1350 +void FMDBBlockSQLiteCallBackFunction(sqlite3_context *context, int argc, sqlite3_value **argv) {
1351 +#if ! __has_feature(objc_arc)
1352 + void (^block)(sqlite3_context *context, int argc, sqlite3_value **argv) = (id)sqlite3_user_data(context);
1353 +#else
1354 + void (^block)(sqlite3_context *context, int argc, sqlite3_value **argv) = (__bridge id)sqlite3_user_data(context);
1355 +#endif
1356 + block(context, argc, argv);
1357 +}
1358 +
1359 +
1360 +- (void)makeFunctionNamed:(NSString*)name maximumArguments:(int)count withBlock:(void (^)(sqlite3_context *context, int argc, sqlite3_value **argv))block {
1361 +
1362 + if (!_openFunctions) {
1363 + _openFunctions = [NSMutableSet new];
1364 + }
1365 +
1366 + id b = FMDBReturnAutoreleased([block copy]);
1367 +
1368 + [_openFunctions addObject:b];
1369 +
1370 + /* 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. */
1371 +#if ! __has_feature(objc_arc)
1372 + sqlite3_create_function([self sqliteHandle], [name UTF8String], count, SQLITE_UTF8, (void*)b, &FMDBBlockSQLiteCallBackFunction, 0x00, 0x00);
1373 +#else
1374 + sqlite3_create_function([self sqliteHandle], [name UTF8String], count, SQLITE_UTF8, (__bridge void*)b, &FMDBBlockSQLiteCallBackFunction, 0x00, 0x00);
1375 +#endif
1376 +}
1377 +
1378 +@end
1379 +
1380 +
1381 +
1382 +@implementation FMStatement
1383 +@synthesize statement=_statement;
1384 +@synthesize query=_query;
1385 +@synthesize useCount=_useCount;
1386 +@synthesize inUse=_inUse;
1387 +
1388 +- (void)finalize {
1389 + [self close];
1390 + [super finalize];
1391 +}
1392 +
1393 +- (void)dealloc {
1394 + [self close];
1395 + FMDBRelease(_query);
1396 +#if ! __has_feature(objc_arc)
1397 + [super dealloc];
1398 +#endif
1399 +}
1400 +
1401 +- (void)close {
1402 + if (_statement) {
1403 + sqlite3_finalize(_statement);
1404 + _statement = 0x00;
1405 + }
1406 +
1407 + _inUse = NO;
1408 +}
1409 +
1410 +- (void)reset {
1411 + if (_statement) {
1412 + sqlite3_reset(_statement);
1413 + }
1414 +
1415 + _inUse = NO;
1416 +}
1417 +
1418 +- (NSString*)description {
1419 + return [NSString stringWithFormat:@"%@ %ld hit(s) for query %@", [super description], _useCount, _query];
1420 +}
1421 +
1422 +
1423 +@end
1424 +
1 +//
2 +// FMDatabaseAdditions.h
3 +// fmdb
4 +//
5 +// Created by August Mueller on 10/30/05.
6 +// Copyright 2005 Flying Meat Inc.. All rights reserved.
7 +//
8 +
9 +#import <Foundation/Foundation.h>
10 +#import "FMDatabase.h"
11 +
12 +
13 +/** Category of additions for `<FMDatabase>` class.
14 +
15 + ### See also
16 +
17 + - `<FMDatabase>`
18 + */
19 +
20 +@interface FMDatabase (FMDatabaseAdditions)
21 +
22 +///----------------------------------------
23 +/// @name Return results of SQL to variable
24 +///----------------------------------------
25 +
26 +/** Return `int` value for query
27 +
28 + @param query The SQL query to be performed.
29 + @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query.
30 +
31 + @return `int` value.
32 +
33 + @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project.
34 + */
35 +
36 +- (int)intForQuery:(NSString*)query, ...;
37 +
38 +/** Return `long` value for query
39 +
40 + @param query The SQL query to be performed.
41 + @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query.
42 +
43 + @return `long` value.
44 +
45 + @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project.
46 + */
47 +
48 +- (long)longForQuery:(NSString*)query, ...;
49 +
50 +/** Return `BOOL` value for query
51 +
52 + @param query The SQL query to be performed.
53 + @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query.
54 +
55 + @return `BOOL` value.
56 +
57 + @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project.
58 + */
59 +
60 +- (BOOL)boolForQuery:(NSString*)query, ...;
61 +
62 +/** Return `double` value for query
63 +
64 + @param query The SQL query to be performed.
65 + @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query.
66 +
67 + @return `double` value.
68 +
69 + @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project.
70 + */
71 +
72 +- (double)doubleForQuery:(NSString*)query, ...;
73 +
74 +/** Return `NSString` value for query
75 +
76 + @param query The SQL query to be performed.
77 + @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query.
78 +
79 + @return `NSString` value.
80 +
81 + @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project.
82 + */
83 +
84 +- (NSString*)stringForQuery:(NSString*)query, ...;
85 +
86 +/** Return `NSData` value for query
87 +
88 + @param query The SQL query to be performed.
89 + @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query.
90 +
91 + @return `NSData` value.
92 +
93 + @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project.
94 + */
95 +
96 +- (NSData*)dataForQuery:(NSString*)query, ...;
97 +
98 +/** Return `NSDate` value for query
99 +
100 + @param query The SQL query to be performed.
101 + @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query.
102 +
103 + @return `NSDate` value.
104 +
105 + @note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project.
106 + */
107 +
108 +- (NSDate*)dateForQuery:(NSString*)query, ...;
109 +
110 +
111 +// Notice that there's no dataNoCopyForQuery:.
112 +// That would be a bad idea, because we close out the result set, and then what
113 +// happens to the data that we just didn't copy? Who knows, not I.
114 +
115 +
116 +///--------------------------------
117 +/// @name Schema related operations
118 +///--------------------------------
119 +
120 +/** Does table exist in database?
121 +
122 + @param tableName The name of the table being looked for.
123 +
124 + @return `YES` if table found; `NO` if not found.
125 + */
126 +
127 +- (BOOL)tableExists:(NSString*)tableName;
128 +
129 +/** The schema of the database.
130 +
131 + This will be the schema for the entire database. For each entity, each row of the result set will include the following fields:
132 +
133 + - `type` - The type of entity (e.g. table, index, view, or trigger)
134 + - `name` - The name of the object
135 + - `tbl_name` - The name of the table to which the object references
136 + - `rootpage` - The page number of the root b-tree page for tables and indices
137 + - `sql` - The SQL that created the entity
138 +
139 + @return `FMResultSet` of schema; `nil` on error.
140 +
141 + @see [SQLite File Format](http://www.sqlite.org/fileformat.html)
142 + */
143 +
144 +- (FMResultSet*)getSchema;
145 +
146 +/** The schema of the database.
147 +
148 + This will be the schema for a particular table as report by SQLite `PRAGMA`, for example:
149 +
150 + PRAGMA table_info('employees')
151 +
152 + This will report:
153 +
154 + - `cid` - The column ID number
155 + - `name` - The name of the column
156 + - `type` - The data type specified for the column
157 + - `notnull` - whether the field is defined as NOT NULL (i.e. values required)
158 + - `dflt_value` - The default value for the column
159 + - `pk` - Whether the field is part of the primary key of the table
160 +
161 + @param tableName The name of the table for whom the schema will be returned.
162 +
163 + @return `FMResultSet` of schema; `nil` on error.
164 +
165 + @see [table_info](http://www.sqlite.org/pragma.html#pragma_table_info)
166 + */
167 +
168 +- (FMResultSet*)getTableSchema:(NSString*)tableName;
169 +
170 +/** Test to see if particular column exists for particular table in database
171 +
172 + @param columnName The name of the column.
173 +
174 + @param tableName The name of the table.
175 +
176 + @return `YES` if column exists in table in question; `NO` otherwise.
177 + */
178 +
179 +- (BOOL)columnExists:(NSString*)columnName inTableWithName:(NSString*)tableName;
180 +
181 +/** Test to see if particular column exists for particular table in database
182 +
183 + @param columnName The name of the column.
184 +
185 + @param tableName The name of the table.
186 +
187 + @return `YES` if column exists in table in question; `NO` otherwise.
188 +
189 + @see columnExists:inTableWithName:
190 +
191 + @warning Deprecated - use `<columnExists:inTableWithName:>` instead.
192 + */
193 +
194 +- (BOOL)columnExists:(NSString*)tableName columnName:(NSString*)columnName __attribute__ ((deprecated));
195 +
196 +
197 +/** Validate SQL statement
198 +
199 + This validates SQL statement by performing `sqlite3_prepare_v2`, but not returning the results, but instead immediately calling `sqlite3_finalize`.
200 +
201 + @param sql The SQL statement being validated.
202 +
203 + @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.
204 +
205 + @return `YES` if validation succeeded without incident; `NO` otherwise.
206 +
207 + */
208 +
209 +- (BOOL)validateSQL:(NSString*)sql error:(NSError**)error;
210 +
211 +
212 +#if SQLITE_VERSION_NUMBER >= 3007017
213 +
214 +///-----------------------------------
215 +/// @name Application identifier tasks
216 +///-----------------------------------
217 +
218 +/** Retrieve application ID
219 +
220 + @return The `uint32_t` numeric value of the application ID.
221 +
222 + @see setApplicationID:
223 + */
224 +
225 +- (uint32_t)applicationID;
226 +
227 +/** Set the application ID
228 +
229 + @param appID The `uint32_t` numeric value of the application ID.
230 +
231 + @see applicationID
232 + */
233 +
234 +- (void)setApplicationID:(uint32_t)appID;
235 +
236 +#if TARGET_OS_MAC && !TARGET_OS_IPHONE
237 +/** Retrieve application ID string
238 +
239 + @return The `NSString` value of the application ID.
240 +
241 + @see setApplicationIDString:
242 + */
243 +
244 +
245 +- (NSString*)applicationIDString;
246 +
247 +/** Set the application ID string
248 +
249 + @param string The `NSString` value of the application ID.
250 +
251 + @see applicationIDString
252 + */
253 +
254 +- (void)setApplicationIDString:(NSString*)string;
255 +#endif
256 +
257 +#endif
258 +
259 +///-----------------------------------
260 +/// @name user version identifier tasks
261 +///-----------------------------------
262 +
263 +/** Retrieve user version
264 +
265 + @return The `uint32_t` numeric value of the user version.
266 +
267 + @see setUserVersion:
268 + */
269 +
270 +- (uint32_t)userVersion;
271 +
272 +/** Set the user-version
273 +
274 + @param version The `uint32_t` numeric value of the user version.
275 +
276 + @see userVersion
277 + */
278 +
279 +- (void)setUserVersion:(uint32_t)version;
280 +
281 +@end
1 +//
2 +// FMDatabaseAdditions.m
3 +// fmdb
4 +//
5 +// Created by August Mueller on 10/30/05.
6 +// Copyright 2005 Flying Meat Inc.. All rights reserved.
7 +//
8 +
9 +#import "FMDatabase.h"
10 +#import "FMDatabaseAdditions.h"
11 +#import "TargetConditionals.h"
12 +
13 +@interface FMDatabase (PrivateStuff)
14 +- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args;
15 +@end
16 +
17 +@implementation FMDatabase (FMDatabaseAdditions)
18 +
19 +#define RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(type, sel) \
20 +va_list args; \
21 +va_start(args, query); \
22 +FMResultSet *resultSet = [self executeQuery:query withArgumentsInArray:0x00 orDictionary:0x00 orVAList:args]; \
23 +va_end(args); \
24 +if (![resultSet next]) { return (type)0; } \
25 +type ret = [resultSet sel:0]; \
26 +[resultSet close]; \
27 +[resultSet setParentDB:nil]; \
28 +return ret;
29 +
30 +
31 +- (NSString*)stringForQuery:(NSString*)query, ... {
32 + RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSString *, stringForColumnIndex);
33 +}
34 +
35 +- (int)intForQuery:(NSString*)query, ... {
36 + RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(int, intForColumnIndex);
37 +}
38 +
39 +- (long)longForQuery:(NSString*)query, ... {
40 + RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(long, longForColumnIndex);
41 +}
42 +
43 +- (BOOL)boolForQuery:(NSString*)query, ... {
44 + RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(BOOL, boolForColumnIndex);
45 +}
46 +
47 +- (double)doubleForQuery:(NSString*)query, ... {
48 + RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(double, doubleForColumnIndex);
49 +}
50 +
51 +- (NSData*)dataForQuery:(NSString*)query, ... {
52 + RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSData *, dataForColumnIndex);
53 +}
54 +
55 +- (NSDate*)dateForQuery:(NSString*)query, ... {
56 + RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSDate *, dateForColumnIndex);
57 +}
58 +
59 +
60 +- (BOOL)tableExists:(NSString*)tableName {
61 +
62 + tableName = [tableName lowercaseString];
63 +
64 + FMResultSet *rs = [self executeQuery:@"select [sql] from sqlite_master where [type] = 'table' and lower(name) = ?", tableName];
65 +
66 + //if at least one next exists, table exists
67 + BOOL returnBool = [rs next];
68 +
69 + //close and free object
70 + [rs close];
71 +
72 + return returnBool;
73 +}
74 +
75 +/*
76 + get table with list of tables: result colums: type[STRING], name[STRING],tbl_name[STRING],rootpage[INTEGER],sql[STRING]
77 + check if table exist in database (patch from OZLB)
78 +*/
79 +- (FMResultSet*)getSchema {
80 +
81 + //result colums: type[STRING], name[STRING],tbl_name[STRING],rootpage[INTEGER],sql[STRING]
82 + 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"];
83 +
84 + return rs;
85 +}
86 +
87 +/*
88 + get table schema: result colums: cid[INTEGER], name,type [STRING], notnull[INTEGER], dflt_value[],pk[INTEGER]
89 +*/
90 +- (FMResultSet*)getTableSchema:(NSString*)tableName {
91 +
92 + //result colums: cid[INTEGER], name,type [STRING], notnull[INTEGER], dflt_value[],pk[INTEGER]
93 + FMResultSet *rs = [self executeQuery:[NSString stringWithFormat: @"pragma table_info('%@')", tableName]];
94 +
95 + return rs;
96 +}
97 +
98 +- (BOOL)columnExists:(NSString*)columnName inTableWithName:(NSString*)tableName {
99 +
100 + BOOL returnBool = NO;
101 +
102 + tableName = [tableName lowercaseString];
103 + columnName = [columnName lowercaseString];
104 +
105 + FMResultSet *rs = [self getTableSchema:tableName];
106 +
107 + //check if column is present in table schema
108 + while ([rs next]) {
109 + if ([[[rs stringForColumn:@"name"] lowercaseString] isEqualToString:columnName]) {
110 + returnBool = YES;
111 + break;
112 + }
113 + }
114 +
115 + //If this is not done FMDatabase instance stays out of pool
116 + [rs close];
117 +
118 + return returnBool;
119 +}
120 +
121 +
122 +#if SQLITE_VERSION_NUMBER >= 3007017
123 +
124 +- (uint32_t)applicationID {
125 +
126 + uint32_t r = 0;
127 +
128 + FMResultSet *rs = [self executeQuery:@"pragma application_id"];
129 +
130 + if ([rs next]) {
131 + r = (uint32_t)[rs longLongIntForColumnIndex:0];
132 + }
133 +
134 + [rs close];
135 +
136 + return r;
137 +}
138 +
139 +- (void)setApplicationID:(uint32_t)appID {
140 + NSString *query = [NSString stringWithFormat:@"pragma application_id=%d", appID];
141 + FMResultSet *rs = [self executeQuery:query];
142 + [rs next];
143 + [rs close];
144 +}
145 +
146 +
147 +#if TARGET_OS_MAC && !TARGET_OS_IPHONE
148 +- (NSString*)applicationIDString {
149 + NSString *s = NSFileTypeForHFSTypeCode([self applicationID]);
150 +
151 + assert([s length] == 6);
152 +
153 + s = [s substringWithRange:NSMakeRange(1, 4)];
154 +
155 +
156 + return s;
157 +
158 +}
159 +
160 +- (void)setApplicationIDString:(NSString*)s {
161 +
162 + if ([s length] != 4) {
163 + NSLog(@"setApplicationIDString: string passed is not exactly 4 chars long. (was %ld)", [s length]);
164 + }
165 +
166 + [self setApplicationID:NSHFSTypeCodeFromFileType([NSString stringWithFormat:@"'%@'", s])];
167 +}
168 +
169 +
170 +#endif
171 +
172 +#endif
173 +
174 +- (uint32_t)userVersion {
175 + uint32_t r = 0;
176 +
177 + FMResultSet *rs = [self executeQuery:@"pragma user_version"];
178 +
179 + if ([rs next]) {
180 + r = (uint32_t)[rs longLongIntForColumnIndex:0];
181 + }
182 +
183 + [rs close];
184 + return r;
185 +}
186 +
187 +- (void)setUserVersion:(uint32_t)version {
188 + NSString *query = [NSString stringWithFormat:@"pragma user_version = %d", version];
189 + FMResultSet *rs = [self executeQuery:query];
190 + [rs next];
191 + [rs close];
192 +}
193 +
194 +#pragma clang diagnostic push
195 +#pragma clang diagnostic ignored "-Wdeprecated-implementations"
196 +
197 +- (BOOL)columnExists:(NSString*)tableName columnName:(NSString*)columnName __attribute__ ((deprecated)) {
198 + return [self columnExists:columnName inTableWithName:tableName];
199 +}
200 +
201 +#pragma clang diagnostic pop
202 +
203 +
204 +- (BOOL)validateSQL:(NSString*)sql error:(NSError**)error {
205 + sqlite3_stmt *pStmt = NULL;
206 + BOOL validationSucceeded = YES;
207 +
208 + int rc = sqlite3_prepare_v2(_db, [sql UTF8String], -1, &pStmt, 0);
209 + if (rc != SQLITE_OK) {
210 + validationSucceeded = NO;
211 + if (error) {
212 + *error = [NSError errorWithDomain:NSCocoaErrorDomain
213 + code:[self lastErrorCode]
214 + userInfo:[NSDictionary dictionaryWithObject:[self lastErrorMessage]
215 + forKey:NSLocalizedDescriptionKey]];
216 + }
217 + }
218 +
219 + sqlite3_finalize(pStmt);
220 +
221 + return validationSucceeded;
222 +}
223 +
224 +@end
1 +//
2 +// FMDatabasePool.h
3 +// fmdb
4 +//
5 +// Created by August Mueller on 6/22/11.
6 +// Copyright 2011 Flying Meat Inc. All rights reserved.
7 +//
8 +
9 +#import <Foundation/Foundation.h>
10 +#import "sqlite3.h"
11 +
12 +@class FMDatabase;
13 +
14 +/** Pool of `<FMDatabase>` objects.
15 +
16 + ### See also
17 +
18 + - `<FMDatabaseQueue>`
19 + - `<FMDatabase>`
20 +
21 + @warning Before using `FMDatabasePool`, please consider using `<FMDatabaseQueue>` instead.
22 +
23 + If you really really really know what you're doing and `FMDatabasePool` is what
24 + you really really need (ie, you're using a read only database), OK you can use
25 + it. But just be careful not to deadlock!
26 +
27 + For an example on deadlocking, search for:
28 + `ONLY_USE_THE_POOL_IF_YOU_ARE_DOING_READS_OTHERWISE_YOULL_DEADLOCK_USE_FMDATABASEQUEUE_INSTEAD`
29 + in the main.m file.
30 + */
31 +
32 +@interface FMDatabasePool : NSObject {
33 + NSString *_path;
34 +
35 + dispatch_queue_t _lockQueue;
36 +
37 + NSMutableArray *_databaseInPool;
38 + NSMutableArray *_databaseOutPool;
39 +
40 + __unsafe_unretained id _delegate;
41 +
42 + NSUInteger _maximumNumberOfDatabasesToCreate;
43 + int _openFlags;
44 +}
45 +
46 +/** Database path */
47 +
48 +@property (atomic, retain) NSString *path;
49 +
50 +/** Delegate object */
51 +
52 +@property (atomic, assign) id delegate;
53 +
54 +/** Maximum number of databases to create */
55 +
56 +@property (atomic, assign) NSUInteger maximumNumberOfDatabasesToCreate;
57 +
58 +/** Open flags */
59 +
60 +@property (atomic, readonly) int openFlags;
61 +
62 +
63 +///---------------------
64 +/// @name Initialization
65 +///---------------------
66 +
67 +/** Create pool using path.
68 +
69 + @param aPath The file path of the database.
70 +
71 + @return The `FMDatabasePool` object. `nil` on error.
72 + */
73 +
74 ++ (instancetype)databasePoolWithPath:(NSString*)aPath;
75 +
76 +/** Create pool using path and specified flags
77 +
78 + @param aPath The file path of the database.
79 + @param openFlags Flags passed to the openWithFlags method of the database
80 +
81 + @return The `FMDatabasePool` object. `nil` on error.
82 + */
83 +
84 ++ (instancetype)databasePoolWithPath:(NSString*)aPath flags:(int)openFlags;
85 +
86 +/** Create pool using path.
87 +
88 + @param aPath The file path of the database.
89 +
90 + @return The `FMDatabasePool` object. `nil` on error.
91 + */
92 +
93 +- (instancetype)initWithPath:(NSString*)aPath;
94 +
95 +/** Create pool using path and specified flags.
96 +
97 + @param aPath The file path of the database.
98 + @param openFlags Flags passed to the openWithFlags method of the database
99 +
100 + @return The `FMDatabasePool` object. `nil` on error.
101 + */
102 +
103 +- (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags;
104 +
105 +///------------------------------------------------
106 +/// @name Keeping track of checked in/out databases
107 +///------------------------------------------------
108 +
109 +/** Number of checked-in databases in pool
110 +
111 + @returns Number of databases
112 + */
113 +
114 +- (NSUInteger)countOfCheckedInDatabases;
115 +
116 +/** Number of checked-out databases in pool
117 +
118 + @returns Number of databases
119 + */
120 +
121 +- (NSUInteger)countOfCheckedOutDatabases;
122 +
123 +/** Total number of databases in pool
124 +
125 + @returns Number of databases
126 + */
127 +
128 +- (NSUInteger)countOfOpenDatabases;
129 +
130 +/** Release all databases in pool */
131 +
132 +- (void)releaseAllDatabases;
133 +
134 +///------------------------------------------
135 +/// @name Perform database operations in pool
136 +///------------------------------------------
137 +
138 +/** Synchronously perform database operations in pool.
139 +
140 + @param block The code to be run on the `FMDatabasePool` pool.
141 + */
142 +
143 +- (void)inDatabase:(void (^)(FMDatabase *db))block;
144 +
145 +/** Synchronously perform database operations in pool using transaction.
146 +
147 + @param block The code to be run on the `FMDatabasePool` pool.
148 + */
149 +
150 +- (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block;
151 +
152 +/** Synchronously perform database operations in pool using deferred transaction.
153 +
154 + @param block The code to be run on the `FMDatabasePool` pool.
155 + */
156 +
157 +- (void)inDeferredTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block;
158 +
159 +#if SQLITE_VERSION_NUMBER >= 3007000
160 +
161 +/** Synchronously perform database operations in pool using save point.
162 +
163 + @param block The code to be run on the `FMDatabasePool` pool.
164 +
165 + @return `NSError` object if error; `nil` if successful.
166 +
167 + @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.
168 +*/
169 +
170 +- (NSError*)inSavePoint:(void (^)(FMDatabase *db, BOOL *rollback))block;
171 +#endif
172 +
173 +@end
174 +
175 +
176 +/** FMDatabasePool delegate category
177 +
178 + This is a category that defines the protocol for the FMDatabasePool delegate
179 + */
180 +
181 +@interface NSObject (FMDatabasePoolDelegate)
182 +
183 +/** Asks the delegate whether database should be added to the pool.
184 +
185 + @param pool The `FMDatabasePool` object.
186 + @param database The `FMDatabase` object.
187 +
188 + @return `YES` if it should add database to pool; `NO` if not.
189 +
190 + */
191 +
192 +- (BOOL)databasePool:(FMDatabasePool*)pool shouldAddDatabaseToPool:(FMDatabase*)database;
193 +
194 +/** Tells the delegate that database was added to the pool.
195 +
196 + @param pool The `FMDatabasePool` object.
197 + @param database The `FMDatabase` object.
198 +
199 + */
200 +
201 +- (void)databasePool:(FMDatabasePool*)pool didAddDatabase:(FMDatabase*)database;
202 +
203 +@end
204 +
1 +//
2 +// FMDatabasePool.m
3 +// fmdb
4 +//
5 +// Created by August Mueller on 6/22/11.
6 +// Copyright 2011 Flying Meat Inc. All rights reserved.
7 +//
8 +
9 +#import "FMDatabasePool.h"
10 +#import "FMDatabase.h"
11 +
12 +@interface FMDatabasePool()
13 +
14 +- (void)pushDatabaseBackInPool:(FMDatabase*)db;
15 +- (FMDatabase*)db;
16 +
17 +@end
18 +
19 +
20 +@implementation FMDatabasePool
21 +@synthesize path=_path;
22 +@synthesize delegate=_delegate;
23 +@synthesize maximumNumberOfDatabasesToCreate=_maximumNumberOfDatabasesToCreate;
24 +@synthesize openFlags=_openFlags;
25 +
26 +
27 ++ (instancetype)databasePoolWithPath:(NSString*)aPath {
28 + return FMDBReturnAutoreleased([[self alloc] initWithPath:aPath]);
29 +}
30 +
31 ++ (instancetype)databasePoolWithPath:(NSString*)aPath flags:(int)openFlags {
32 + return FMDBReturnAutoreleased([[self alloc] initWithPath:aPath flags:openFlags]);
33 +}
34 +
35 +- (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags {
36 +
37 + self = [super init];
38 +
39 + if (self != nil) {
40 + _path = [aPath copy];
41 + _lockQueue = dispatch_queue_create([[NSString stringWithFormat:@"fmdb.%@", self] UTF8String], NULL);
42 + _databaseInPool = FMDBReturnRetained([NSMutableArray array]);
43 + _databaseOutPool = FMDBReturnRetained([NSMutableArray array]);
44 + _openFlags = openFlags;
45 + }
46 +
47 + return self;
48 +}
49 +
50 +- (instancetype)initWithPath:(NSString*)aPath
51 +{
52 + // default flags for sqlite3_open
53 + return [self initWithPath:aPath flags:SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE];
54 +}
55 +
56 +- (instancetype)init {
57 + return [self initWithPath:nil];
58 +}
59 +
60 +
61 +- (void)dealloc {
62 +
63 + _delegate = 0x00;
64 + FMDBRelease(_path);
65 + FMDBRelease(_databaseInPool);
66 + FMDBRelease(_databaseOutPool);
67 +
68 + if (_lockQueue) {
69 + FMDBDispatchQueueRelease(_lockQueue);
70 + _lockQueue = 0x00;
71 + }
72 +#if ! __has_feature(objc_arc)
73 + [super dealloc];
74 +#endif
75 +}
76 +
77 +
78 +- (void)executeLocked:(void (^)(void))aBlock {
79 + dispatch_sync(_lockQueue, aBlock);
80 +}
81 +
82 +- (void)pushDatabaseBackInPool:(FMDatabase*)db {
83 +
84 + if (!db) { // db can be null if we set an upper bound on the # of databases to create.
85 + return;
86 + }
87 +
88 + [self executeLocked:^() {
89 +
90 + if ([self->_databaseInPool containsObject:db]) {
91 + [[NSException exceptionWithName:@"Database already in pool" reason:@"The FMDatabase being put back into the pool is already present in the pool" userInfo:nil] raise];
92 + }
93 +
94 + [self->_databaseInPool addObject:db];
95 + [self->_databaseOutPool removeObject:db];
96 +
97 + }];
98 +}
99 +
100 +- (FMDatabase*)db {
101 +
102 + __block FMDatabase *db;
103 +
104 +
105 + [self executeLocked:^() {
106 + db = [self->_databaseInPool lastObject];
107 +
108 + BOOL shouldNotifyDelegate = NO;
109 +
110 + if (db) {
111 + [self->_databaseOutPool addObject:db];
112 + [self->_databaseInPool removeLastObject];
113 + }
114 + else {
115 +
116 + if (self->_maximumNumberOfDatabasesToCreate) {
117 + NSUInteger currentCount = [self->_databaseOutPool count] + [self->_databaseInPool count];
118 +
119 + if (currentCount >= self->_maximumNumberOfDatabasesToCreate) {
120 + NSLog(@"Maximum number of databases (%ld) has already been reached!", (long)currentCount);
121 + return;
122 + }
123 + }
124 +
125 + db = [FMDatabase databaseWithPath:self->_path];
126 + shouldNotifyDelegate = YES;
127 + }
128 +
129 + //This ensures that the db is opened before returning
130 +#if SQLITE_VERSION_NUMBER >= 3005000
131 + BOOL success = [db openWithFlags:self->_openFlags];
132 +#else
133 + BOOL success = [db open];
134 +#endif
135 + if (success) {
136 + if ([self->_delegate respondsToSelector:@selector(databasePool:shouldAddDatabaseToPool:)] && ![self->_delegate databasePool:self shouldAddDatabaseToPool:db]) {
137 + [db close];
138 + db = 0x00;
139 + }
140 + else {
141 + //It should not get added in the pool twice if lastObject was found
142 + if (![self->_databaseOutPool containsObject:db]) {
143 + [self->_databaseOutPool addObject:db];
144 +
145 + if (shouldNotifyDelegate && [self->_delegate respondsToSelector:@selector(databasePool:didAddDatabase:)]) {
146 + [self->_delegate databasePool:self didAddDatabase:db];
147 + }
148 + }
149 + }
150 + }
151 + else {
152 + NSLog(@"Could not open up the database at path %@", self->_path);
153 + db = 0x00;
154 + }
155 + }];
156 +
157 + return db;
158 +}
159 +
160 +- (NSUInteger)countOfCheckedInDatabases {
161 +
162 + __block NSUInteger count;
163 +
164 + [self executeLocked:^() {
165 + count = [self->_databaseInPool count];
166 + }];
167 +
168 + return count;
169 +}
170 +
171 +- (NSUInteger)countOfCheckedOutDatabases {
172 +
173 + __block NSUInteger count;
174 +
175 + [self executeLocked:^() {
176 + count = [self->_databaseOutPool count];
177 + }];
178 +
179 + return count;
180 +}
181 +
182 +- (NSUInteger)countOfOpenDatabases {
183 + __block NSUInteger count;
184 +
185 + [self executeLocked:^() {
186 + count = [self->_databaseOutPool count] + [self->_databaseInPool count];
187 + }];
188 +
189 + return count;
190 +}
191 +
192 +- (void)releaseAllDatabases {
193 + [self executeLocked:^() {
194 + [self->_databaseOutPool removeAllObjects];
195 + [self->_databaseInPool removeAllObjects];
196 + }];
197 +}
198 +
199 +- (void)inDatabase:(void (^)(FMDatabase *db))block {
200 +
201 + FMDatabase *db = [self db];
202 +
203 + block(db);
204 +
205 + [self pushDatabaseBackInPool:db];
206 +}
207 +
208 +- (void)beginTransaction:(BOOL)useDeferred withBlock:(void (^)(FMDatabase *db, BOOL *rollback))block {
209 +
210 + BOOL shouldRollback = NO;
211 +
212 + FMDatabase *db = [self db];
213 +
214 + if (useDeferred) {
215 + [db beginDeferredTransaction];
216 + }
217 + else {
218 + [db beginTransaction];
219 + }
220 +
221 +
222 + block(db, &shouldRollback);
223 +
224 + if (shouldRollback) {
225 + [db rollback];
226 + }
227 + else {
228 + [db commit];
229 + }
230 +
231 + [self pushDatabaseBackInPool:db];
232 +}
233 +
234 +- (void)inDeferredTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block {
235 + [self beginTransaction:YES withBlock:block];
236 +}
237 +
238 +- (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block {
239 + [self beginTransaction:NO withBlock:block];
240 +}
241 +#if SQLITE_VERSION_NUMBER >= 3007000
242 +- (NSError*)inSavePoint:(void (^)(FMDatabase *db, BOOL *rollback))block {
243 +
244 + static unsigned long savePointIdx = 0;
245 +
246 + NSString *name = [NSString stringWithFormat:@"savePoint%ld", savePointIdx++];
247 +
248 + BOOL shouldRollback = NO;
249 +
250 + FMDatabase *db = [self db];
251 +
252 + NSError *err = 0x00;
253 +
254 + if (![db startSavePointWithName:name error:&err]) {
255 + [self pushDatabaseBackInPool:db];
256 + return err;
257 + }
258 +
259 + block(db, &shouldRollback);
260 +
261 + if (shouldRollback) {
262 + // We need to rollback and release this savepoint to remove it
263 + [db rollbackToSavePointWithName:name error:&err];
264 + }
265 + [db releaseSavePointWithName:name error:&err];
266 +
267 + [self pushDatabaseBackInPool:db];
268 +
269 + return err;
270 +}
271 +#endif
272 +
273 +@end
1 +//
2 +// FMDatabaseQueue.h
3 +// fmdb
4 +//
5 +// Created by August Mueller on 6/22/11.
6 +// Copyright 2011 Flying Meat Inc. All rights reserved.
7 +//
8 +
9 +#import <Foundation/Foundation.h>
10 +#import "sqlite3.h"
11 +
12 +@class FMDatabase;
13 +
14 +/** To perform queries and updates on multiple threads, you'll want to use `FMDatabaseQueue`.
15 +
16 + 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.
17 +
18 + Instead, use `FMDatabaseQueue`. Here's how to use it:
19 +
20 + First, make your queue.
21 +
22 + FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:aPath];
23 +
24 + Then use it like so:
25 +
26 + [queue inDatabase:^(FMDatabase *db) {
27 + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]];
28 + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]];
29 + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]];
30 +
31 + FMResultSet *rs = [db executeQuery:@"select * from foo"];
32 + while ([rs next]) {
33 + //…
34 + }
35 + }];
36 +
37 + An easy way to wrap things up in a transaction can be done like this:
38 +
39 + [queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
40 + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]];
41 + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]];
42 + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]];
43 +
44 + if (whoopsSomethingWrongHappened) {
45 + *rollback = YES;
46 + return;
47 + }
48 + // etc…
49 + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:4]];
50 + }];
51 +
52 + `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.
53 +
54 + ### See also
55 +
56 + - `<FMDatabase>`
57 +
58 + @warning Do not instantiate a single `<FMDatabase>` object and use it across multiple threads. Use `FMDatabaseQueue` instead.
59 +
60 + @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.
61 +
62 + */
63 +
64 +@interface FMDatabaseQueue : NSObject {
65 + NSString *_path;
66 + dispatch_queue_t _queue;
67 + FMDatabase *_db;
68 + int _openFlags;
69 +}
70 +
71 +/** Path of database */
72 +
73 +@property (atomic, retain) NSString *path;
74 +
75 +/** Open flags */
76 +
77 +@property (atomic, readonly) int openFlags;
78 +
79 +///----------------------------------------------------
80 +/// @name Initialization, opening, and closing of queue
81 +///----------------------------------------------------
82 +
83 +/** Create queue using path.
84 +
85 + @param aPath The file path of the database.
86 +
87 + @return The `FMDatabaseQueue` object. `nil` on error.
88 + */
89 +
90 ++ (instancetype)databaseQueueWithPath:(NSString*)aPath;
91 +
92 +/** Create queue using path and specified flags.
93 +
94 + @param aPath The file path of the database.
95 + @param openFlags Flags passed to the openWithFlags method of the database
96 +
97 + @return The `FMDatabaseQueue` object. `nil` on error.
98 + */
99 ++ (instancetype)databaseQueueWithPath:(NSString*)aPath flags:(int)openFlags;
100 +
101 +/** Create queue using path.
102 +
103 + @param aPath The file path of the database.
104 +
105 + @return The `FMDatabaseQueue` object. `nil` on error.
106 + */
107 +
108 +- (instancetype)initWithPath:(NSString*)aPath;
109 +
110 +/** Create queue using path and specified flags.
111 +
112 + @param aPath The file path of the database.
113 + @param openFlags Flags passed to the openWithFlags method of the database
114 +
115 + @return The `FMDatabaseQueue` object. `nil` on error.
116 + */
117 +
118 +- (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags;
119 +
120 +/** Returns the Class of 'FMDatabase' subclass, that will be used to instantiate database object.
121 +
122 + Subclasses can override this method to return specified Class of 'FMDatabase' subclass.
123 +
124 + @return The Class of 'FMDatabase' subclass, that will be used to instantiate database object.
125 + */
126 +
127 ++ (Class)databaseClass;
128 +
129 +/** Close database used by queue. */
130 +
131 +- (void)close;
132 +
133 +///-----------------------------------------------
134 +/// @name Dispatching database operations to queue
135 +///-----------------------------------------------
136 +
137 +/** Synchronously perform database operations on queue.
138 +
139 + @param block The code to be run on the queue of `FMDatabaseQueue`
140 + */
141 +
142 +- (void)inDatabase:(void (^)(FMDatabase *db))block;
143 +
144 +/** Synchronously perform database operations on queue, using transactions.
145 +
146 + @param block The code to be run on the queue of `FMDatabaseQueue`
147 + */
148 +
149 +- (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block;
150 +
151 +/** Synchronously perform database operations on queue, using deferred transactions.
152 +
153 + @param block The code to be run on the queue of `FMDatabaseQueue`
154 + */
155 +
156 +- (void)inDeferredTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block;
157 +
158 +///-----------------------------------------------
159 +/// @name Dispatching database operations to queue
160 +///-----------------------------------------------
161 +
162 +/** Synchronously perform database operations using save point.
163 +
164 + @param block The code to be run on the queue of `FMDatabaseQueue`
165 + */
166 +
167 +#if SQLITE_VERSION_NUMBER >= 3007000
168 +// NOTE: you can not nest these, since calling it will pull another database out of the pool and you'll get a deadlock.
169 +// If you need to nest, use FMDatabase's startSavePointWithName:error: instead.
170 +- (NSError*)inSavePoint:(void (^)(FMDatabase *db, BOOL *rollback))block;
171 +#endif
172 +
173 +@end
174 +
1 +//
2 +// FMDatabaseQueue.m
3 +// fmdb
4 +//
5 +// Created by August Mueller on 6/22/11.
6 +// Copyright 2011 Flying Meat Inc. All rights reserved.
7 +//
8 +
9 +#import "FMDatabaseQueue.h"
10 +#import "FMDatabase.h"
11 +
12 +/*
13 +
14 + Note: we call [self retain]; before using dispatch_sync, just incase
15 + FMDatabaseQueue is released on another thread and we're in the middle of doing
16 + something in dispatch_sync
17 +
18 + */
19 +
20 +/*
21 + * A key used to associate the FMDatabaseQueue object with the dispatch_queue_t it uses.
22 + * This in turn is used for deadlock detection by seeing if inDatabase: is called on
23 + * the queue's dispatch queue, which should not happen and causes a deadlock.
24 + */
25 +static const void * const kDispatchQueueSpecificKey = &kDispatchQueueSpecificKey;
26 +
27 +@implementation FMDatabaseQueue
28 +
29 +@synthesize path = _path;
30 +@synthesize openFlags = _openFlags;
31 +
32 ++ (instancetype)databaseQueueWithPath:(NSString*)aPath {
33 +
34 + FMDatabaseQueue *q = [[self alloc] initWithPath:aPath];
35 +
36 + FMDBAutorelease(q);
37 +
38 + return q;
39 +}
40 +
41 ++ (instancetype)databaseQueueWithPath:(NSString*)aPath flags:(int)openFlags {
42 +
43 + FMDatabaseQueue *q = [[self alloc] initWithPath:aPath flags:openFlags];
44 +
45 + FMDBAutorelease(q);
46 +
47 + return q;
48 +}
49 +
50 ++ (Class)databaseClass {
51 + return [FMDatabase class];
52 +}
53 +
54 +- (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags {
55 +
56 + self = [super init];
57 +
58 + if (self != nil) {
59 +
60 + _db = [[[self class] databaseClass] databaseWithPath:aPath];
61 + FMDBRetain(_db);
62 +
63 +#if SQLITE_VERSION_NUMBER >= 3005000
64 + BOOL success = [_db openWithFlags:openFlags];
65 +#else
66 + BOOL success = [_db open];
67 +#endif
68 + if (!success) {
69 + NSLog(@"Could not create database queue for path %@", aPath);
70 + FMDBRelease(self);
71 + return 0x00;
72 + }
73 +
74 + _path = FMDBReturnRetained(aPath);
75 +
76 + _queue = dispatch_queue_create([[NSString stringWithFormat:@"fmdb.%@", self] UTF8String], NULL);
77 + dispatch_queue_set_specific(_queue, kDispatchQueueSpecificKey, (__bridge void *)self, NULL);
78 + _openFlags = openFlags;
79 + }
80 +
81 + return self;
82 +}
83 +
84 +- (instancetype)initWithPath:(NSString*)aPath {
85 +
86 + // default flags for sqlite3_open
87 + return [self initWithPath:aPath flags:SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE];
88 +}
89 +
90 +- (instancetype)init {
91 + return [self initWithPath:nil];
92 +}
93 +
94 +
95 +- (void)dealloc {
96 +
97 + FMDBRelease(_db);
98 + FMDBRelease(_path);
99 +
100 + if (_queue) {
101 + FMDBDispatchQueueRelease(_queue);
102 + _queue = 0x00;
103 + }
104 +#if ! __has_feature(objc_arc)
105 + [super dealloc];
106 +#endif
107 +}
108 +
109 +- (void)close {
110 + FMDBRetain(self);
111 + dispatch_sync(_queue, ^() {
112 + [self->_db close];
113 + FMDBRelease(_db);
114 + self->_db = 0x00;
115 + });
116 + FMDBRelease(self);
117 +}
118 +
119 +- (FMDatabase*)database {
120 + if (!_db) {
121 + _db = FMDBReturnRetained([FMDatabase databaseWithPath:_path]);
122 +
123 +#if SQLITE_VERSION_NUMBER >= 3005000
124 + BOOL success = [_db openWithFlags:_openFlags];
125 +#else
126 + BOOL success = [_db open];
127 +#endif
128 + if (!success) {
129 + NSLog(@"FMDatabaseQueue could not reopen database for path %@", _path);
130 + FMDBRelease(_db);
131 + _db = 0x00;
132 + return 0x00;
133 + }
134 + }
135 +
136 + return _db;
137 +}
138 +
139 +- (void)inDatabase:(void (^)(FMDatabase *db))block {
140 + /* Get the currently executing queue (which should probably be nil, but in theory could be another DB queue
141 + * and then check it against self to make sure we're not about to deadlock. */
142 + FMDatabaseQueue *currentSyncQueue = (__bridge id)dispatch_get_specific(kDispatchQueueSpecificKey);
143 + assert(currentSyncQueue != self && "inDatabase: was called reentrantly on the same queue, which would lead to a deadlock");
144 +
145 + FMDBRetain(self);
146 +
147 + dispatch_sync(_queue, ^() {
148 +
149 + FMDatabase *db = [self database];
150 + block(db);
151 +
152 + if ([db hasOpenResultSets]) {
153 + NSLog(@"Warning: there is at least one open result set around after performing [FMDatabaseQueue inDatabase:]");
154 +
155 +#if defined(DEBUG) && DEBUG
156 + NSSet *openSetCopy = FMDBReturnAutoreleased([[db valueForKey:@"_openResultSets"] copy]);
157 + for (NSValue *rsInWrappedInATastyValueMeal in openSetCopy) {
158 + FMResultSet *rs = (FMResultSet *)[rsInWrappedInATastyValueMeal pointerValue];
159 + NSLog(@"query: '%@'", [rs query]);
160 + }
161 +#endif
162 + }
163 + });
164 +
165 + FMDBRelease(self);
166 +}
167 +
168 +
169 +- (void)beginTransaction:(BOOL)useDeferred withBlock:(void (^)(FMDatabase *db, BOOL *rollback))block {
170 + FMDBRetain(self);
171 + dispatch_sync(_queue, ^() {
172 +
173 + BOOL shouldRollback = NO;
174 +
175 + if (useDeferred) {
176 + [[self database] beginDeferredTransaction];
177 + }
178 + else {
179 + [[self database] beginTransaction];
180 + }
181 +
182 + block([self database], &shouldRollback);
183 +
184 + if (shouldRollback) {
185 + [[self database] rollback];
186 + }
187 + else {
188 + [[self database] commit];
189 + }
190 + });
191 +
192 + FMDBRelease(self);
193 +}
194 +
195 +- (void)inDeferredTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block {
196 + [self beginTransaction:YES withBlock:block];
197 +}
198 +
199 +- (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block {
200 + [self beginTransaction:NO withBlock:block];
201 +}
202 +
203 +#if SQLITE_VERSION_NUMBER >= 3007000
204 +- (NSError*)inSavePoint:(void (^)(FMDatabase *db, BOOL *rollback))block {
205 +
206 + static unsigned long savePointIdx = 0;
207 + __block NSError *err = 0x00;
208 + FMDBRetain(self);
209 + dispatch_sync(_queue, ^() {
210 +
211 + NSString *name = [NSString stringWithFormat:@"savePoint%ld", savePointIdx++];
212 +
213 + BOOL shouldRollback = NO;
214 +
215 + if ([[self database] startSavePointWithName:name error:&err]) {
216 +
217 + block([self database], &shouldRollback);
218 +
219 + if (shouldRollback) {
220 + // We need to rollback and release this savepoint to remove it
221 + [[self database] rollbackToSavePointWithName:name error:&err];
222 + }
223 + [[self database] releaseSavePointWithName:name error:&err];
224 +
225 + }
226 + });
227 + FMDBRelease(self);
228 + return err;
229 +}
230 +#endif
231 +
232 +@end
1 +#import <Foundation/Foundation.h>
2 +#import "sqlite3.h"
3 +
4 +#ifndef __has_feature // Optional.
5 +#define __has_feature(x) 0 // Compatibility with non-clang compilers.
6 +#endif
7 +
8 +#ifndef NS_RETURNS_NOT_RETAINED
9 +#if __has_feature(attribute_ns_returns_not_retained)
10 +#define NS_RETURNS_NOT_RETAINED __attribute__((ns_returns_not_retained))
11 +#else
12 +#define NS_RETURNS_NOT_RETAINED
13 +#endif
14 +#endif
15 +
16 +@class FMDatabase;
17 +@class FMStatement;
18 +
19 +/** Represents the results of executing a query on an `<FMDatabase>`.
20 +
21 + ### See also
22 +
23 + - `<FMDatabase>`
24 + */
25 +
26 +@interface FMResultSet : NSObject {
27 + FMDatabase *_parentDB;
28 + FMStatement *_statement;
29 +
30 + NSString *_query;
31 + NSMutableDictionary *_columnNameToIndexMap;
32 +}
33 +
34 +///-----------------
35 +/// @name Properties
36 +///-----------------
37 +
38 +/** Executed query */
39 +
40 +@property (atomic, retain) NSString *query;
41 +
42 +/** `NSMutableDictionary` mapping column names to numeric index */
43 +
44 +@property (readonly) NSMutableDictionary *columnNameToIndexMap;
45 +
46 +/** `FMStatement` used by result set. */
47 +
48 +@property (atomic, retain) FMStatement *statement;
49 +
50 +///------------------------------------
51 +/// @name Creating and closing database
52 +///------------------------------------
53 +
54 +/** Create result set from `<FMStatement>`
55 +
56 + @param statement A `<FMStatement>` to be performed
57 +
58 + @param aDB A `<FMDatabase>` to be used
59 +
60 + @return A `FMResultSet` on success; `nil` on failure
61 + */
62 +
63 ++ (instancetype)resultSetWithStatement:(FMStatement *)statement usingParentDatabase:(FMDatabase*)aDB;
64 +
65 +/** Close result set */
66 +
67 +- (void)close;
68 +
69 +- (void)setParentDB:(FMDatabase *)newDb;
70 +
71 +///---------------------------------------
72 +/// @name Iterating through the result set
73 +///---------------------------------------
74 +
75 +/** Retrieve next row for result set.
76 +
77 + You must always invoke `next` or `nextWithError` before attempting to access the values returned in a query, even if you're only expecting one.
78 +
79 + @return `YES` if row successfully retrieved; `NO` if end of result set reached
80 +
81 + @see hasAnotherRow
82 + */
83 +
84 +- (BOOL)next;
85 +
86 +/** Retrieve next row for result set.
87 +
88 + You must always invoke `next` or `nextWithError` before attempting to access the values returned in a query, even if you're only expecting one.
89 +
90 + @param outErr A 'NSError' object to receive any error object (if any).
91 +
92 + @return 'YES' if row successfully retrieved; 'NO' if end of result set reached
93 +
94 + @see hasAnotherRow
95 + */
96 +
97 +- (BOOL)nextWithError:(NSError **)outErr;
98 +
99 +/** Did the last call to `<next>` succeed in retrieving another row?
100 +
101 + @return `YES` if the last call to `<next>` succeeded in retrieving another record; `NO` if not.
102 +
103 + @see next
104 +
105 + @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.
106 + */
107 +
108 +- (BOOL)hasAnotherRow;
109 +
110 +///---------------------------------------------
111 +/// @name Retrieving information from result set
112 +///---------------------------------------------
113 +
114 +/** How many columns in result set
115 +
116 + @return Integer value of the number of columns.
117 + */
118 +
119 +- (int)columnCount;
120 +
121 +/** Column index for column name
122 +
123 + @param columnName `NSString` value of the name of the column.
124 +
125 + @return Zero-based index for column.
126 + */
127 +
128 +- (int)columnIndexForName:(NSString*)columnName;
129 +
130 +/** Column name for column index
131 +
132 + @param columnIdx Zero-based index for column.
133 +
134 + @return columnName `NSString` value of the name of the column.
135 + */
136 +
137 +- (NSString*)columnNameForIndex:(int)columnIdx;
138 +
139 +/** Result set integer value for column.
140 +
141 + @param columnName `NSString` value of the name of the column.
142 +
143 + @return `int` value of the result set's column.
144 + */
145 +
146 +- (int)intForColumn:(NSString*)columnName;
147 +
148 +/** Result set integer value for column.
149 +
150 + @param columnIdx Zero-based index for column.
151 +
152 + @return `int` value of the result set's column.
153 + */
154 +
155 +- (int)intForColumnIndex:(int)columnIdx;
156 +
157 +/** Result set `long` value for column.
158 +
159 + @param columnName `NSString` value of the name of the column.
160 +
161 + @return `long` value of the result set's column.
162 + */
163 +
164 +- (long)longForColumn:(NSString*)columnName;
165 +
166 +/** Result set long value for column.
167 +
168 + @param columnIdx Zero-based index for column.
169 +
170 + @return `long` value of the result set's column.
171 + */
172 +
173 +- (long)longForColumnIndex:(int)columnIdx;
174 +
175 +/** Result set `long long int` value for column.
176 +
177 + @param columnName `NSString` value of the name of the column.
178 +
179 + @return `long long int` value of the result set's column.
180 + */
181 +
182 +- (long long int)longLongIntForColumn:(NSString*)columnName;
183 +
184 +/** Result set `long long int` value for column.
185 +
186 + @param columnIdx Zero-based index for column.
187 +
188 + @return `long long int` value of the result set's column.
189 + */
190 +
191 +- (long long int)longLongIntForColumnIndex:(int)columnIdx;
192 +
193 +/** Result set `unsigned long long int` value for column.
194 +
195 + @param columnName `NSString` value of the name of the column.
196 +
197 + @return `unsigned long long int` value of the result set's column.
198 + */
199 +
200 +- (unsigned long long int)unsignedLongLongIntForColumn:(NSString*)columnName;
201 +
202 +/** Result set `unsigned long long int` value for column.
203 +
204 + @param columnIdx Zero-based index for column.
205 +
206 + @return `unsigned long long int` value of the result set's column.
207 + */
208 +
209 +- (unsigned long long int)unsignedLongLongIntForColumnIndex:(int)columnIdx;
210 +
211 +/** Result set `BOOL` value for column.
212 +
213 + @param columnName `NSString` value of the name of the column.
214 +
215 + @return `BOOL` value of the result set's column.
216 + */
217 +
218 +- (BOOL)boolForColumn:(NSString*)columnName;
219 +
220 +/** Result set `BOOL` value for column.
221 +
222 + @param columnIdx Zero-based index for column.
223 +
224 + @return `BOOL` value of the result set's column.
225 + */
226 +
227 +- (BOOL)boolForColumnIndex:(int)columnIdx;
228 +
229 +/** Result set `double` value for column.
230 +
231 + @param columnName `NSString` value of the name of the column.
232 +
233 + @return `double` value of the result set's column.
234 +
235 + */
236 +
237 +- (double)doubleForColumn:(NSString*)columnName;
238 +
239 +/** Result set `double` value for column.
240 +
241 + @param columnIdx Zero-based index for column.
242 +
243 + @return `double` value of the result set's column.
244 +
245 + */
246 +
247 +- (double)doubleForColumnIndex:(int)columnIdx;
248 +
249 +/** Result set `NSString` value for column.
250 +
251 + @param columnName `NSString` value of the name of the column.
252 +
253 + @return `NSString` value of the result set's column.
254 +
255 + */
256 +
257 +- (NSString*)stringForColumn:(NSString*)columnName;
258 +
259 +/** Result set `NSString` value for column.
260 +
261 + @param columnIdx Zero-based index for column.
262 +
263 + @return `NSString` value of the result set's column.
264 + */
265 +
266 +- (NSString*)stringForColumnIndex:(int)columnIdx;
267 +
268 +/** Result set `NSDate` value for column.
269 +
270 + @param columnName `NSString` value of the name of the column.
271 +
272 + @return `NSDate` value of the result set's column.
273 + */
274 +
275 +- (NSDate*)dateForColumn:(NSString*)columnName;
276 +
277 +/** Result set `NSDate` value for column.
278 +
279 + @param columnIdx Zero-based index for column.
280 +
281 + @return `NSDate` value of the result set's column.
282 +
283 + */
284 +
285 +- (NSDate*)dateForColumnIndex:(int)columnIdx;
286 +
287 +/** Result set `NSData` value for column.
288 +
289 + This is useful when storing binary data in table (such as image or the like).
290 +
291 + @param columnName `NSString` value of the name of the column.
292 +
293 + @return `NSData` value of the result set's column.
294 +
295 + */
296 +
297 +- (NSData*)dataForColumn:(NSString*)columnName;
298 +
299 +/** Result set `NSData` value for column.
300 +
301 + @param columnIdx Zero-based index for column.
302 +
303 + @return `NSData` value of the result set's column.
304 + */
305 +
306 +- (NSData*)dataForColumnIndex:(int)columnIdx;
307 +
308 +/** Result set `(const unsigned char *)` value for column.
309 +
310 + @param columnName `NSString` value of the name of the column.
311 +
312 + @return `(const unsigned char *)` value of the result set's column.
313 + */
314 +
315 +- (const unsigned char *)UTF8StringForColumnName:(NSString*)columnName;
316 +
317 +/** Result set `(const unsigned char *)` value for column.
318 +
319 + @param columnIdx Zero-based index for column.
320 +
321 + @return `(const unsigned char *)` value of the result set's column.
322 + */
323 +
324 +- (const unsigned char *)UTF8StringForColumnIndex:(int)columnIdx;
325 +
326 +/** Result set object for column.
327 +
328 + @param columnName `NSString` value of the name of the column.
329 +
330 + @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object.
331 +
332 + @see objectForKeyedSubscript:
333 + */
334 +
335 +- (id)objectForColumnName:(NSString*)columnName;
336 +
337 +/** Result set object for column.
338 +
339 + @param columnIdx Zero-based index for column.
340 +
341 + @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object.
342 +
343 + @see objectAtIndexedSubscript:
344 + */
345 +
346 +- (id)objectForColumnIndex:(int)columnIdx;
347 +
348 +/** Result set object for column.
349 +
350 + 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:
351 +
352 + id result = rs[@"employee_name"];
353 +
354 + This simplified syntax is equivalent to calling:
355 +
356 + id result = [rs objectForKeyedSubscript:@"employee_name"];
357 +
358 + which is, it turns out, equivalent to calling:
359 +
360 + id result = [rs objectForColumnName:@"employee_name"];
361 +
362 + @param columnName `NSString` value of the name of the column.
363 +
364 + @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object.
365 + */
366 +
367 +- (id)objectForKeyedSubscript:(NSString *)columnName;
368 +
369 +/** Result set object for column.
370 +
371 + 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:
372 +
373 + id result = rs[0];
374 +
375 + This simplified syntax is equivalent to calling:
376 +
377 + id result = [rs objectForKeyedSubscript:0];
378 +
379 + which is, it turns out, equivalent to calling:
380 +
381 + id result = [rs objectForColumnName:0];
382 +
383 + @param columnIdx Zero-based index for column.
384 +
385 + @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object.
386 + */
387 +
388 +- (id)objectAtIndexedSubscript:(int)columnIdx;
389 +
390 +/** Result set `NSData` value for column.
391 +
392 + @param columnName `NSString` value of the name of the column.
393 +
394 + @return `NSData` value of the result set's column.
395 +
396 + @warning If you are going to use this data after you iterate over the next row, or after you close the
397 +result set, make sure to make a copy of the data first (or just use `<dataForColumn:>`/`<dataForColumnIndex:>`)
398 +If you don't, you're going to be in a world of hurt when you try and use the data.
399 +
400 + */
401 +
402 +- (NSData*)dataNoCopyForColumn:(NSString*)columnName NS_RETURNS_NOT_RETAINED;
403 +
404 +/** Result set `NSData` value for column.
405 +
406 + @param columnIdx Zero-based index for column.
407 +
408 + @return `NSData` value of the result set's column.
409 +
410 + @warning If you are going to use this data after you iterate over the next row, or after you close the
411 + result set, make sure to make a copy of the data first (or just use `<dataForColumn:>`/`<dataForColumnIndex:>`)
412 + If you don't, you're going to be in a world of hurt when you try and use the data.
413 +
414 + */
415 +
416 +- (NSData*)dataNoCopyForColumnIndex:(int)columnIdx NS_RETURNS_NOT_RETAINED;
417 +
418 +/** Is the column `NULL`?
419 +
420 + @param columnIdx Zero-based index for column.
421 +
422 + @return `YES` if column is `NULL`; `NO` if not `NULL`.
423 + */
424 +
425 +- (BOOL)columnIndexIsNull:(int)columnIdx;
426 +
427 +/** Is the column `NULL`?
428 +
429 + @param columnName `NSString` value of the name of the column.
430 +
431 + @return `YES` if column is `NULL`; `NO` if not `NULL`.
432 + */
433 +
434 +- (BOOL)columnIsNull:(NSString*)columnName;
435 +
436 +
437 +/** Returns a dictionary of the row results mapped to case sensitive keys of the column names.
438 +
439 + @returns `NSDictionary` of the row results.
440 +
441 + @warning The keys to the dictionary are case sensitive of the column names.
442 + */
443 +
444 +- (NSDictionary*)resultDictionary;
445 +
446 +/** Returns a dictionary of the row results
447 +
448 + @see resultDictionary
449 +
450 + @warning **Deprecated**: Please use `<resultDictionary>` instead. Also, beware that `<resultDictionary>` is case sensitive!
451 + */
452 +
453 +- (NSDictionary*)resultDict __attribute__ ((deprecated));
454 +
455 +///-----------------------------
456 +/// @name Key value coding magic
457 +///-----------------------------
458 +
459 +/** Performs `setValue` to yield support for key value observing.
460 +
461 + @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.
462 +
463 + */
464 +
465 +- (void)kvcMagic:(id)object;
466 +
467 +
468 +@end
469 +
1 +#import "FMResultSet.h"
2 +#import "FMDatabase.h"
3 +#import "unistd.h"
4 +
5 +@interface FMDatabase ()
6 +- (void)resultSetDidClose:(FMResultSet *)resultSet;
7 +@end
8 +
9 +
10 +@implementation FMResultSet
11 +@synthesize query=_query;
12 +@synthesize statement=_statement;
13 +
14 ++ (instancetype)resultSetWithStatement:(FMStatement *)statement usingParentDatabase:(FMDatabase*)aDB {
15 +
16 + FMResultSet *rs = [[FMResultSet alloc] init];
17 +
18 + [rs setStatement:statement];
19 + [rs setParentDB:aDB];
20 +
21 + NSParameterAssert(![statement inUse]);
22 + [statement setInUse:YES]; // weak reference
23 +
24 + return FMDBReturnAutoreleased(rs);
25 +}
26 +
27 +- (void)finalize {
28 + [self close];
29 + [super finalize];
30 +}
31 +
32 +- (void)dealloc {
33 + [self close];
34 +
35 + FMDBRelease(_query);
36 + _query = nil;
37 +
38 + FMDBRelease(_columnNameToIndexMap);
39 + _columnNameToIndexMap = nil;
40 +
41 +#if ! __has_feature(objc_arc)
42 + [super dealloc];
43 +#endif
44 +}
45 +
46 +- (void)close {
47 + [_statement reset];
48 + FMDBRelease(_statement);
49 + _statement = nil;
50 +
51 + // we don't need this anymore... (i think)
52 + //[_parentDB setInUse:NO];
53 + [_parentDB resultSetDidClose:self];
54 + _parentDB = nil;
55 +}
56 +
57 +- (int)columnCount {
58 + return sqlite3_column_count([_statement statement]);
59 +}
60 +
61 +- (NSMutableDictionary *)columnNameToIndexMap {
62 + if (!_columnNameToIndexMap) {
63 + int columnCount = sqlite3_column_count([_statement statement]);
64 + _columnNameToIndexMap = [[NSMutableDictionary alloc] initWithCapacity:(NSUInteger)columnCount];
65 + int columnIdx = 0;
66 + for (columnIdx = 0; columnIdx < columnCount; columnIdx++) {
67 + [_columnNameToIndexMap setObject:[NSNumber numberWithInt:columnIdx]
68 + forKey:[[NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)] lowercaseString]];
69 + }
70 + }
71 + return _columnNameToIndexMap;
72 +}
73 +
74 +- (void)kvcMagic:(id)object {
75 +
76 + int columnCount = sqlite3_column_count([_statement statement]);
77 +
78 + int columnIdx = 0;
79 + for (columnIdx = 0; columnIdx < columnCount; columnIdx++) {
80 +
81 + const char *c = (const char *)sqlite3_column_text([_statement statement], columnIdx);
82 +
83 + // check for a null row
84 + if (c) {
85 + NSString *s = [NSString stringWithUTF8String:c];
86 +
87 + [object setValue:s forKey:[NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)]];
88 + }
89 + }
90 +}
91 +
92 +#pragma clang diagnostic push
93 +#pragma clang diagnostic ignored "-Wdeprecated-implementations"
94 +
95 +- (NSDictionary*)resultDict {
96 +
97 + NSUInteger num_cols = (NSUInteger)sqlite3_data_count([_statement statement]);
98 +
99 + if (num_cols > 0) {
100 + NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:num_cols];
101 +
102 + NSEnumerator *columnNames = [[self columnNameToIndexMap] keyEnumerator];
103 + NSString *columnName = nil;
104 + while ((columnName = [columnNames nextObject])) {
105 + id objectValue = [self objectForColumnName:columnName];
106 + [dict setObject:objectValue forKey:columnName];
107 + }
108 +
109 + return FMDBReturnAutoreleased([dict copy]);
110 + }
111 + else {
112 + NSLog(@"Warning: There seem to be no columns in this set.");
113 + }
114 +
115 + return nil;
116 +}
117 +
118 +#pragma clang diagnostic pop
119 +
120 +- (NSDictionary*)resultDictionary {
121 +
122 + NSUInteger num_cols = (NSUInteger)sqlite3_data_count([_statement statement]);
123 +
124 + if (num_cols > 0) {
125 + NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:num_cols];
126 +
127 + int columnCount = sqlite3_column_count([_statement statement]);
128 +
129 + int columnIdx = 0;
130 + for (columnIdx = 0; columnIdx < columnCount; columnIdx++) {
131 +
132 + NSString *columnName = [NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)];
133 + id objectValue = [self objectForColumnIndex:columnIdx];
134 + [dict setObject:objectValue forKey:columnName];
135 + }
136 +
137 + return dict;
138 + }
139 + else {
140 + NSLog(@"Warning: There seem to be no columns in this set.");
141 + }
142 +
143 + return nil;
144 +}
145 +
146 +
147 +
148 +
149 +- (BOOL)next {
150 + return [self nextWithError:nil];
151 +}
152 +
153 +- (BOOL)nextWithError:(NSError **)outErr {
154 +
155 + int rc = sqlite3_step([_statement statement]);
156 +
157 + if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) {
158 + NSLog(@"%s:%d Database busy (%@)", __FUNCTION__, __LINE__, [_parentDB databasePath]);
159 + NSLog(@"Database busy");
160 + if (outErr) {
161 + *outErr = [_parentDB lastError];
162 + }
163 + }
164 + else if (SQLITE_DONE == rc || SQLITE_ROW == rc) {
165 + // all is well, let's return.
166 + }
167 + else if (SQLITE_ERROR == rc) {
168 + NSLog(@"Error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle]));
169 + if (outErr) {
170 + *outErr = [_parentDB lastError];
171 + }
172 + }
173 + else if (SQLITE_MISUSE == rc) {
174 + // uh oh.
175 + NSLog(@"Error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle]));
176 + if (outErr) {
177 + if (_parentDB) {
178 + *outErr = [_parentDB lastError];
179 + }
180 + else {
181 + // If 'next' or 'nextWithError' is called after the result set is closed,
182 + // we need to return the appropriate error.
183 + NSDictionary* errorMessage = [NSDictionary dictionaryWithObject:@"parentDB does not exist" forKey:NSLocalizedDescriptionKey];
184 + *outErr = [NSError errorWithDomain:@"FMDatabase" code:SQLITE_MISUSE userInfo:errorMessage];
185 + }
186 +
187 + }
188 + }
189 + else {
190 + // wtf?
191 + NSLog(@"Unknown error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle]));
192 + if (outErr) {
193 + *outErr = [_parentDB lastError];
194 + }
195 + }
196 +
197 +
198 + if (rc != SQLITE_ROW) {
199 + [self close];
200 + }
201 +
202 + return (rc == SQLITE_ROW);
203 +}
204 +
205 +- (BOOL)hasAnotherRow {
206 + return sqlite3_errcode([_parentDB sqliteHandle]) == SQLITE_ROW;
207 +}
208 +
209 +- (int)columnIndexForName:(NSString*)columnName {
210 + columnName = [columnName lowercaseString];
211 +
212 + NSNumber *n = [[self columnNameToIndexMap] objectForKey:columnName];
213 +
214 + if (n) {
215 + return [n intValue];
216 + }
217 +
218 + NSLog(@"Warning: I could not find the column named '%@'.", columnName);
219 +
220 + return -1;
221 +}
222 +
223 +
224 +
225 +- (int)intForColumn:(NSString*)columnName {
226 + return [self intForColumnIndex:[self columnIndexForName:columnName]];
227 +}
228 +
229 +- (int)intForColumnIndex:(int)columnIdx {
230 + return sqlite3_column_int([_statement statement], columnIdx);
231 +}
232 +
233 +- (long)longForColumn:(NSString*)columnName {
234 + return [self longForColumnIndex:[self columnIndexForName:columnName]];
235 +}
236 +
237 +- (long)longForColumnIndex:(int)columnIdx {
238 + return (long)sqlite3_column_int64([_statement statement], columnIdx);
239 +}
240 +
241 +- (long long int)longLongIntForColumn:(NSString*)columnName {
242 + return [self longLongIntForColumnIndex:[self columnIndexForName:columnName]];
243 +}
244 +
245 +- (long long int)longLongIntForColumnIndex:(int)columnIdx {
246 + return sqlite3_column_int64([_statement statement], columnIdx);
247 +}
248 +
249 +- (unsigned long long int)unsignedLongLongIntForColumn:(NSString*)columnName {
250 + return [self unsignedLongLongIntForColumnIndex:[self columnIndexForName:columnName]];
251 +}
252 +
253 +- (unsigned long long int)unsignedLongLongIntForColumnIndex:(int)columnIdx {
254 + return (unsigned long long int)[self longLongIntForColumnIndex:columnIdx];
255 +}
256 +
257 +- (BOOL)boolForColumn:(NSString*)columnName {
258 + return [self boolForColumnIndex:[self columnIndexForName:columnName]];
259 +}
260 +
261 +- (BOOL)boolForColumnIndex:(int)columnIdx {
262 + return ([self intForColumnIndex:columnIdx] != 0);
263 +}
264 +
265 +- (double)doubleForColumn:(NSString*)columnName {
266 + return [self doubleForColumnIndex:[self columnIndexForName:columnName]];
267 +}
268 +
269 +- (double)doubleForColumnIndex:(int)columnIdx {
270 + return sqlite3_column_double([_statement statement], columnIdx);
271 +}
272 +
273 +- (NSString*)stringForColumnIndex:(int)columnIdx {
274 +
275 + if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0)) {
276 + return nil;
277 + }
278 +
279 + const char *c = (const char *)sqlite3_column_text([_statement statement], columnIdx);
280 +
281 + if (!c) {
282 + // null row.
283 + return nil;
284 + }
285 +
286 + return [NSString stringWithUTF8String:c];
287 +}
288 +
289 +- (NSString*)stringForColumn:(NSString*)columnName {
290 + return [self stringForColumnIndex:[self columnIndexForName:columnName]];
291 +}
292 +
293 +- (NSDate*)dateForColumn:(NSString*)columnName {
294 + return [self dateForColumnIndex:[self columnIndexForName:columnName]];
295 +}
296 +
297 +- (NSDate*)dateForColumnIndex:(int)columnIdx {
298 +
299 + if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0)) {
300 + return nil;
301 + }
302 +
303 + return [_parentDB hasDateFormatter] ? [_parentDB dateFromString:[self stringForColumnIndex:columnIdx]] : [NSDate dateWithTimeIntervalSince1970:[self doubleForColumnIndex:columnIdx]];
304 +}
305 +
306 +
307 +- (NSData*)dataForColumn:(NSString*)columnName {
308 + return [self dataForColumnIndex:[self columnIndexForName:columnName]];
309 +}
310 +
311 +- (NSData*)dataForColumnIndex:(int)columnIdx {
312 +
313 + if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0)) {
314 + return nil;
315 + }
316 +
317 + const char *dataBuffer = sqlite3_column_blob([_statement statement], columnIdx);
318 + int dataSize = sqlite3_column_bytes([_statement statement], columnIdx);
319 +
320 + if (dataBuffer == NULL) {
321 + return nil;
322 + }
323 +
324 + return [NSData dataWithBytes:(const void *)dataBuffer length:(NSUInteger)dataSize];
325 +}
326 +
327 +
328 +- (NSData*)dataNoCopyForColumn:(NSString*)columnName {
329 + return [self dataNoCopyForColumnIndex:[self columnIndexForName:columnName]];
330 +}
331 +
332 +- (NSData*)dataNoCopyForColumnIndex:(int)columnIdx {
333 +
334 + if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0)) {
335 + return nil;
336 + }
337 +
338 + const char *dataBuffer = sqlite3_column_blob([_statement statement], columnIdx);
339 + int dataSize = sqlite3_column_bytes([_statement statement], columnIdx);
340 +
341 + NSData *data = [NSData dataWithBytesNoCopy:(void *)dataBuffer length:(NSUInteger)dataSize freeWhenDone:NO];
342 +
343 + return data;
344 +}
345 +
346 +
347 +- (BOOL)columnIndexIsNull:(int)columnIdx {
348 + return sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL;
349 +}
350 +
351 +- (BOOL)columnIsNull:(NSString*)columnName {
352 + return [self columnIndexIsNull:[self columnIndexForName:columnName]];
353 +}
354 +
355 +- (const unsigned char *)UTF8StringForColumnIndex:(int)columnIdx {
356 +
357 + if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0)) {
358 + return nil;
359 + }
360 +
361 + return sqlite3_column_text([_statement statement], columnIdx);
362 +}
363 +
364 +- (const unsigned char *)UTF8StringForColumnName:(NSString*)columnName {
365 + return [self UTF8StringForColumnIndex:[self columnIndexForName:columnName]];
366 +}
367 +
368 +- (id)objectForColumnIndex:(int)columnIdx {
369 + int columnType = sqlite3_column_type([_statement statement], columnIdx);
370 +
371 + id returnValue = nil;
372 +
373 + if (columnType == SQLITE_INTEGER) {
374 + returnValue = [NSNumber numberWithLongLong:[self longLongIntForColumnIndex:columnIdx]];
375 + }
376 + else if (columnType == SQLITE_FLOAT) {
377 + returnValue = [NSNumber numberWithDouble:[self doubleForColumnIndex:columnIdx]];
378 + }
379 + else if (columnType == SQLITE_BLOB) {
380 + returnValue = [self dataForColumnIndex:columnIdx];
381 + }
382 + else {
383 + //default to a string for everything else
384 + returnValue = [self stringForColumnIndex:columnIdx];
385 + }
386 +
387 + if (returnValue == nil) {
388 + returnValue = [NSNull null];
389 + }
390 +
391 + return returnValue;
392 +}
393 +
394 +- (id)objectForColumnName:(NSString*)columnName {
395 + return [self objectForColumnIndex:[self columnIndexForName:columnName]];
396 +}
397 +
398 +// returns autoreleased NSString containing the name of the column in the result set
399 +- (NSString*)columnNameForIndex:(int)columnIdx {
400 + return [NSString stringWithUTF8String: sqlite3_column_name([_statement statement], columnIdx)];
401 +}
402 +
403 +- (void)setParentDB:(FMDatabase *)newDb {
404 + _parentDB = newDb;
405 +}
406 +
407 +- (id)objectAtIndexedSubscript:(int)columnIdx {
408 + return [self objectForColumnIndex:columnIdx];
409 +}
410 +
411 +- (id)objectForKeyedSubscript:(NSString *)columnName {
412 + return [self objectForColumnName:columnName];
413 +}
414 +
415 +
416 +@end
1 +//
2 +// NSData+SSToolkitAdditions.h
3 +// SSToolkit
4 +//
5 +// Created by Sam Soffes on 9/29/08.
6 +// Copyright 2008-2011 Sam Soffes. All rights reserved.
7 +//
8 +
9 +/**
10 + Provides extensions to `NSData` for various common tasks.
11 + */
12 +@import UIKit;
13 +@interface NSData (SSToolkitAdditions)
14 +
15 +///--------------
16 +/// @name Hashing
17 +///--------------
18 +
19 +/**
20 + Returns a string of the MD5 sum of the receiver.
21 +
22 + @return The string of the MD5 sum of the receiver.
23 + */
24 +- (NSString *)MD5Sum;
25 +
26 +/**
27 + Returns a string of the SHA1 sum of the receiver.
28 +
29 + @return The string of the SHA1 sum of the receiver.
30 + */
31 +- (NSString *)SHA1Sum;
32 +
33 +/**
34 + Returns a string of the SHA256 sum of the receiver.
35 +
36 + @return The string of the SHA256 sum of the receiver.
37 + */
38 +- (NSString *)SHA256Sum;
39 +
40 +
41 +///-----------------------------------
42 +/// @name Base64 Encoding and Decoding
43 +///-----------------------------------
44 +
45 +/**
46 + Returns a string representation of the receiver Base64 encoded.
47 +
48 + @return A Base64 encoded string
49 + */
50 +- (NSString *)base64EncodedString;
51 +
52 +/**
53 + Returns a new data contained in the Base64 encoded string.
54 +
55 + @param base64String A Base64 encoded string
56 +
57 + @return Data contained in `base64String`
58 + */
59 ++ (NSData *)dataWithBase64String:(NSString *)base64String;
60 +
61 +@end
...\ No newline at end of file ...\ No newline at end of file
1 +//
2 +// NSData+SSToolkitAdditions.m
3 +// SSToolkit
4 +//
5 +// Created by Sam Soffes on 9/29/08.
6 +// Copyright 2008-2011 Sam Soffes. All rights reserved.
7 +//
8 +
9 +#import "NSData+SSToolkitAdditions.h"
10 +#include <CommonCrypto/CommonDigest.h>
11 +
12 +static const char _base64EncodingTable[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
13 +static const short _base64DecodingTable[256] = {
14 + -2, -2, -2, -2, -2, -2, -2, -2, -2, -1, -1, -2, -1, -1, -2, -2,
15 + -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
16 + -1, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, 62, -2, -2, -2, 63,
17 + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -2, -2, -2, -2, -2, -2,
18 + -2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
19 + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -2, -2, -2, -2, -2,
20 + -2, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
21 + 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -2, -2, -2, -2, -2,
22 + -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
23 + -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
24 + -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
25 + -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
26 + -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
27 + -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
28 + -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
29 + -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2
30 +};
31 +
32 +@implementation NSData (SSToolkitAdditions)
33 +
34 +- (NSString *)MD5Sum {
35 + unsigned char digest[CC_MD5_DIGEST_LENGTH], i;
36 + CC_MD5(self.bytes, (CC_LONG)self.length, digest);
37 +
38 + NSMutableString *ms = [NSMutableString string];
39 + for (i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
40 + [ms appendFormat: @"%02x", (int)(digest[i])];
41 + }
42 + return [ms copy];
43 +}
44 +
45 +
46 +- (NSString *)SHA1Sum {
47 + NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
48 + uint8_t digest[CC_SHA1_DIGEST_LENGTH];
49 + CC_SHA1(self.bytes, (CC_LONG)self.length, digest);
50 + for (NSInteger i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) {
51 + [output appendFormat:@"%02x", digest[i]];
52 + }
53 + return output;
54 +}
55 +
56 +
57 +- (NSString *)SHA256Sum {
58 + NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2];
59 + uint8_t digest[CC_SHA256_DIGEST_LENGTH];
60 + CC_SHA256(self.bytes, (CC_LONG)self.length, digest);
61 + for (NSInteger i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) {
62 + [output appendFormat:@"%02x", digest[i]];
63 + }
64 + return output;
65 +}
66 +
67 +
68 +// Adapted from http://www.cocoadev.com/index.pl?BaseSixtyFour
69 +- (NSString *)base64EncodedString {
70 + const uint8_t *input = self.bytes;
71 + NSInteger length = self.length;
72 +
73 + NSMutableData *data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
74 + uint8_t *output = (uint8_t *)data.mutableBytes;
75 +
76 + for (NSInteger i = 0; i < length; i += 3) {
77 + NSInteger value = 0;
78 + for (NSInteger j = i; j < (i + 3); j++) {
79 + value <<= 8;
80 +
81 + if (j < length) {
82 + value |= (0xFF & input[j]);
83 + }
84 + }
85 +
86 + NSInteger index = (i / 3) * 4;
87 + output[index + 0] = _base64EncodingTable[(value >> 18) & 0x3F];
88 + output[index + 1] = _base64EncodingTable[(value >> 12) & 0x3F];
89 + output[index + 2] = (i + 1) < length ? _base64EncodingTable[(value >> 6) & 0x3F] : '=';
90 + output[index + 3] = (i + 2) < length ? _base64EncodingTable[(value >> 0) & 0x3F] : '=';
91 + }
92 +
93 + return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
94 +}
95 +
96 +
97 +// Adapted from http://www.cocoadev.com/index.pl?BaseSixtyFour
98 ++ (NSData *)dataWithBase64String:(NSString *)base64String {
99 + const char *string = [base64String cStringUsingEncoding:NSASCIIStringEncoding];
100 + NSInteger inputLength = base64String.length;
101 +
102 + if (string == NULL/* || inputLength % 4 != 0*/) {
103 + return nil;
104 + }
105 +
106 + while (inputLength > 0 && string[inputLength - 1] == '=') {
107 + inputLength--;
108 + }
109 +
110 + NSInteger outputLength = inputLength * 3 / 4;
111 + NSMutableData* data = [NSMutableData dataWithLength:outputLength];
112 + uint8_t *output = data.mutableBytes;
113 +
114 + NSInteger inputPoint = 0;
115 + NSInteger outputPoint = 0;
116 + while (inputPoint < inputLength) {
117 + char i0 = string[inputPoint++];
118 + char i1 = string[inputPoint++];
119 + char i2 = inputPoint < inputLength ? string[inputPoint++] : 'A'; /* 'A' will decode to \0 */
120 + char i3 = inputPoint < inputLength ? string[inputPoint++] : 'A';
121 +
122 + output[outputPoint++] = (_base64DecodingTable[i0] << 2) | (_base64DecodingTable[i1] >> 4);
123 + if (outputPoint < outputLength) {
124 + output[outputPoint++] = ((_base64DecodingTable[i1] & 0xf) << 4) | (_base64DecodingTable[i2] >> 2);
125 + }
126 + if (outputPoint < outputLength) {
127 + output[outputPoint++] = ((_base64DecodingTable[i2] & 0x3) << 6) | _base64DecodingTable[i3];
128 + }
129 + }
130 +
131 + return data;
132 +}
133 +
134 +@end
...\ No newline at end of file ...\ No newline at end of file
1 +//
2 +// NSString+SSToolkitAdditions.h
3 +// SSToolkit
4 +//
5 +// Created by Sam Soffes on 6/22/09.
6 +// Copyright 2009-2011 Sam Soffes. All rights reserved.
7 +//
8 +
9 +/**
10 + Provides extensions to `NSString` for various common tasks.
11 + */
12 +@import UIKit;
13 +@interface NSString (SSToolkitAdditions)
14 +
15 +///------------------------
16 +/// @name Checking Contents
17 +///------------------------
18 +
19 +/**
20 + Returns a Boolean if the receiver contains the given `string`.
21 +
22 + @param string A string to test the the receiver for
23 +
24 + @return A Boolean if the receiver contains the given `string`
25 + */
26 +- (BOOL)containsString:(NSString *)string;
27 +
28 +
29 +///--------------
30 +/// @name Hashing
31 +///--------------
32 +
33 +/**
34 + Returns a string of the MD5 sum of the receiver.
35 +
36 + @return The string of the MD5 sum of the receiver.
37 + */
38 +- (NSString *)MD5Sum;
39 +
40 +/**
41 + Returns a string of the SHA1 sum of the receiver.
42 +
43 + @return The string of the SHA1 sum of the receiver.
44 + */
45 +- (NSString *)SHA1Sum;
46 +
47 +/**
48 + Returns a string of the SHA256 sum of the receiver.
49 +
50 + @return The string of the SHA256 sum of the receiver.
51 + */
52 +- (NSString *)SHA256Sum;
53 +
54 +
55 +///-------------------------
56 +/// @name Comparing Versions
57 +///-------------------------
58 +
59 +/**
60 + Returns a comparison result for the receiver and a given `version`.
61 +
62 + Examples:
63 +
64 + <pre><code>[@"10.4" compareToVersionString:@"10.3"]; // NSOrderedDescending
65 + [@"10.5" compareToVersionString:@"10.5.0"]; // NSOrderedSame
66 + [@"10.4 Build 8L127" compareToVersionString:@"10.4 Build 8P135"]; // NSOrderedAscending</code></pre>
67 +
68 + @param version A version string to compare to the receiver
69 +
70 + @return A comparison result for the receiver and a given `version`
71 + */
72 +- (NSComparisonResult)compareToVersionString:(NSString *)version;
73 +
74 +
75 +///-----------------------------------
76 +/// @name HTML Escaping and Unescaping
77 +///-----------------------------------
78 +
79 +/**
80 + Returns a new string with any HTML escaped.
81 +
82 + @return A new string with any HTML escaped.
83 +
84 + @see unescapeHTML
85 + */
86 +- (NSString *)escapeHTML;
87 +
88 +/**
89 + Returns a new string with any HTML unescaped.
90 +
91 + @return A new string with any HTML unescaped.
92 +
93 + @see escapeHTML
94 + */
95 +- (NSString *)unescapeHTML;
96 +
97 +
98 +///----------------------------------
99 +/// @name URL Escaping and Unescaping
100 +///----------------------------------
101 +
102 +/**
103 + Returns a new string escaped for a URL query parameter.
104 +
105 + The following characters are escaped: `\n\r:/=,!$&'()*+;[]@#?%`. Spaces are escaped to the `+` character. (`+` is
106 + escaped to `%2B`).
107 +
108 + @return A new string escaped for a URL query parameter.
109 +
110 + @see stringByUnescapingFromURLQuery
111 + */
112 +- (NSString *)stringByEscapingForURLQuery;
113 +
114 +/**
115 + Returns a new string unescaped from a URL query parameter.
116 +
117 + `+` characters are unescaped to spaces.
118 +
119 + @return A new string escaped for a URL query parameter.
120 +
121 + @see stringByEscapingForURLQuery
122 + */
123 +- (NSString *)stringByUnescapingFromURLQuery;
124 +
125 +
126 +///-----------------------------------------------
127 +/// @name URL Encoding and Unencoding (Deprecated)
128 +///-----------------------------------------------
129 +
130 +/**
131 + Returns a new string encoded for a URL. (Deprecated)
132 +
133 + The following characters are encoded: `:/=,!$&'()*+;[]@#?%`.
134 +
135 + @return A new string escaped for a URL.
136 + */
137 +- (NSString *)URLEncodedString;
138 +
139 +/**
140 + Returns a new string encoded for a URL parameter. (Deprecated)
141 +
142 + The following characters are encoded: `:/=,!$&'()*+;[]@#?`.
143 +
144 + @return A new string escaped for a URL parameter.
145 + */
146 +- (NSString *)URLEncodedParameterString;
147 +
148 +/**
149 + Returns a new string decoded from a URL.
150 +
151 + @return A new string decoded from a URL.
152 + */
153 +- (NSString *)URLDecodedString;
154 +
155 +
156 +///----------------------
157 +/// @name Base64 Encoding
158 +///----------------------
159 +
160 +/**
161 + Returns a string representation of the receiver Base64 encoded.
162 +
163 + @return A Base64 encoded string
164 + */
165 +- (NSString *)base64EncodedString;
166 +
167 +/**
168 + Returns a new string contained in the Base64 encoded string.
169 +
170 + This uses `NSData`'s `dataWithBase64String:` method to do the conversion then initializes a string with the resulting
171 + `NSData` object using `NSUTF8StringEncoding`.
172 +
173 + @param base64String A Base64 encoded string
174 +
175 + @return String contained in `base64String`
176 + */
177 ++ (NSString *)stringWithBase64String:(NSString *)base64String;
178 +
179 +
180 +///------------------------
181 +/// @name Generating a UUID
182 +///------------------------
183 +
184 +/**
185 + Returns a new string containing a Universally Unique Identifier.
186 + */
187 ++ (NSString *)stringWithUUID;
188 +
189 +///---------------
190 +/// @name Trimming
191 +///---------------
192 +
193 +/**
194 + Returns a new string by trimming leading and trailing characters in a given `NSCharacterSet`.
195 +
196 + @param characterSet Character set to trim characters
197 +
198 + @return A new string by trimming leading and trailing characters in `characterSet`
199 + */
200 +- (NSString *)stringByTrimmingLeadingAndTrailingCharactersInSet:(NSCharacterSet *)characterSet;
201 +
202 +/**
203 + Returns a new string by trimming leading and trailing whitespace and newline characters.
204 +
205 + @return A new string by trimming leading and trailing whitespace and newline characters
206 + */
207 +- (NSString *)stringByTrimmingLeadingAndTrailingWhitespaceAndNewlineCharacters;
208 +
209 +/**
210 + Returns a new string by trimming leading characters in a given `NSCharacterSet`.
211 +
212 + @param characterSet Character set to trim characters
213 +
214 + @return A new string by trimming leading characters in `characterSet`
215 + */
216 +- (NSString *)stringByTrimmingLeadingCharactersInSet:(NSCharacterSet *)characterSet;
217 +
218 +/**
219 + Returns a new string by trimming leading whitespace and newline characters.
220 +
221 + @return A new string by trimming leading whitespace and newline characters
222 + */
223 +- (NSString *)stringByTrimmingLeadingWhitespaceAndNewlineCharacters;
224 +
225 +/**
226 + Returns a new string by trimming trailing characters in a given `NSCharacterSet`.
227 +
228 + @param characterSet Character set to trim characters
229 +
230 + @return A new string by trimming trailing characters in `characterSet`
231 + */
232 +- (NSString *)stringByTrimmingTrailingCharactersInSet:(NSCharacterSet *)characterSet;
233 +
234 +/**
235 + Returns a new string by trimming trailing whitespace and newline characters.
236 +
237 + @return A new string by trimming trailing whitespace and newline characters
238 + */
239 +- (NSString *)stringByTrimmingTrailingWhitespaceAndNewlineCharacters;
240 +
241 +@end
...\ No newline at end of file ...\ No newline at end of file
1 +//
2 +// NSString+SSToolkitAdditions.m
3 +// SSToolkit
4 +//
5 +// Created by Sam Soffes on 6/22/09.
6 +// Copyright 2009-2011 Sam Soffes. All rights reserved.
7 +//
8 +
9 +#import "NSString+SSToolkitAdditions.h"
10 +#import "NSData+SSToolkitAdditions.h"
11 +#import <CommonCrypto/CommonDigest.h>
12 +
13 +@implementation NSString (SSToolkitAdditions)
14 +
15 +- (BOOL)containsString:(NSString *)string {
16 + return !NSEqualRanges([self rangeOfString:string], NSMakeRange(NSNotFound, 0));
17 +}
18 +
19 +
20 +- (NSString *)MD5Sum {
21 + const char *cstr = [self cStringUsingEncoding:NSUTF8StringEncoding];
22 + NSData *data = [NSData dataWithBytes:cstr length:self.length];
23 + return [data MD5Sum];
24 +}
25 +
26 +
27 +- (NSString *)SHA1Sum {
28 + const char *cstr = [self cStringUsingEncoding:NSUTF8StringEncoding];
29 + NSData *data = [NSData dataWithBytes:cstr length:self.length];
30 + return [data SHA1Sum];
31 +}
32 +
33 +
34 +- (NSString *)SHA256Sum {
35 + const char *cstr = [self cStringUsingEncoding:NSUTF8StringEncoding];
36 + NSData *data = [NSData dataWithBytes:cstr length:self.length];
37 + return [data SHA256Sum];
38 +}
39 +
40 +
41 +// Adapted from http://snipplr.com/view/2771/compare-two-version-strings
42 +- (NSComparisonResult)compareToVersionString:(NSString *)version {
43 + // Break version into fields (separated by '.')
44 + NSMutableArray *leftFields = [[NSMutableArray alloc] initWithArray:[self componentsSeparatedByString:@"."]];
45 + NSMutableArray *rightFields = [[NSMutableArray alloc] initWithArray:[version componentsSeparatedByString:@"."]];
46 +
47 + // Implict ".0" in case version doesn't have the same number of '.'
48 + if ([leftFields count] < [rightFields count]) {
49 + while ([leftFields count] != [rightFields count]) {
50 + [leftFields addObject:@"0"];
51 + }
52 + } else if ([leftFields count] > [rightFields count]) {
53 + while ([leftFields count] != [rightFields count]) {
54 + [rightFields addObject:@"0"];
55 + }
56 + }
57 +
58 + // Do a numeric comparison on each field
59 + for (NSUInteger i = 0; i < [leftFields count]; i++) {
60 + NSComparisonResult result = [[leftFields objectAtIndex:i] compare:[rightFields objectAtIndex:i] options:NSNumericSearch];
61 + if (result != NSOrderedSame) {
62 + return result;
63 + }
64 + }
65 +
66 + return NSOrderedSame;
67 +}
68 +
69 +
70 +#pragma mark - HTML Methods
71 +
72 +- (NSString *)escapeHTML {
73 + NSMutableString *s = [NSMutableString string];
74 +
75 + NSUInteger start = 0;
76 + NSUInteger len = [self length];
77 + NSCharacterSet *chs = [NSCharacterSet characterSetWithCharactersInString:@"<>&\""];
78 +
79 + while (start < len) {
80 + NSRange r = [self rangeOfCharacterFromSet:chs options:0 range:NSMakeRange(start, len-start)];
81 + if (r.location == NSNotFound) {
82 + [s appendString:[self substringFromIndex:start]];
83 + break;
84 + }
85 +
86 + if (start < r.location) {
87 + [s appendString:[self substringWithRange:NSMakeRange(start, r.location-start)]];
88 + }
89 +
90 + switch ([self characterAtIndex:r.location]) {
91 + case '<':
92 + [s appendString:@"&lt;"];
93 + break;
94 + case '>':
95 + [s appendString:@"&gt;"];
96 + break;
97 + case '"':
98 + [s appendString:@"&quot;"];
99 + break;
100 + // case '…':
101 + // [s appendString:@"&hellip;"];
102 + // break;
103 + case '&':
104 + [s appendString:@"&amp;"];
105 + break;
106 + }
107 +
108 + start = r.location + 1;
109 + }
110 +
111 + return s;
112 +}
113 +
114 +
115 +- (NSString *)unescapeHTML {
116 + NSMutableString *s = [NSMutableString string];
117 + NSMutableString *target = [self mutableCopy];
118 + NSCharacterSet *chs = [NSCharacterSet characterSetWithCharactersInString:@"&"];
119 +
120 + while ([target length] > 0) {
121 + NSRange r = [target rangeOfCharacterFromSet:chs];
122 + if (r.location == NSNotFound) {
123 + [s appendString:target];
124 + break;
125 + }
126 +
127 + if (r.location > 0) {
128 + [s appendString:[target substringToIndex:r.location]];
129 + [target deleteCharactersInRange:NSMakeRange(0, r.location)];
130 + }
131 +
132 + if ([target hasPrefix:@"&lt;"]) {
133 + [s appendString:@"<"];
134 + [target deleteCharactersInRange:NSMakeRange(0, 4)];
135 + } else if ([target hasPrefix:@"&gt;"]) {
136 + [s appendString:@">"];
137 + [target deleteCharactersInRange:NSMakeRange(0, 4)];
138 + } else if ([target hasPrefix:@"&quot;"]) {
139 + [s appendString:@"\""];
140 + [target deleteCharactersInRange:NSMakeRange(0, 6)];
141 + } else if ([target hasPrefix:@"&#39;"]) {
142 + [s appendString:@"'"];
143 + [target deleteCharactersInRange:NSMakeRange(0, 5)];
144 + } else if ([target hasPrefix:@"&amp;"]) {
145 + [s appendString:@"&"];
146 + [target deleteCharactersInRange:NSMakeRange(0, 5)];
147 + } else if ([target hasPrefix:@"&hellip;"]) {
148 + [s appendString:@"…"];
149 + [target deleteCharactersInRange:NSMakeRange(0, 8)];
150 + } else {
151 + [s appendString:@"&"];
152 + [target deleteCharactersInRange:NSMakeRange(0, 1)];
153 + }
154 + }
155 +
156 + return s;
157 +}
158 +
159 +
160 +#pragma mark - URL Escaping and Unescaping
161 +
162 +- (NSString *)stringByEscapingForURLQuery {
163 + NSString *result = self;
164 +
165 + static CFStringRef leaveAlone = CFSTR(" ");
166 + static CFStringRef toEscape = CFSTR("\n\r:/=,!$&'()*+;[]@#?%");
167 +
168 + CFStringRef escapedStr = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)self, leaveAlone,
169 + toEscape, kCFStringEncodingUTF8);
170 +
171 + if (escapedStr) {
172 + NSMutableString *mutable = [NSMutableString stringWithString:(__bridge NSString *)escapedStr];
173 + CFRelease(escapedStr);
174 +
175 + [mutable replaceOccurrencesOfString:@" " withString:@"+" options:0 range:NSMakeRange(0, [mutable length])];
176 + result = mutable;
177 + }
178 + return result;
179 +}
180 +
181 +
182 +- (NSString *)stringByUnescapingFromURLQuery {
183 + NSString *deplussed = [self stringByReplacingOccurrencesOfString:@"+" withString:@" "];
184 + return [deplussed stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
185 +}
186 +
187 +
188 +#pragma mark - URL Encoding and Unencoding (Deprecated)
189 +
190 +- (NSString *)URLEncodedString {
191 + static CFStringRef toEscape = CFSTR(":/=,!$&'()*+;[]@#?%");
192 + return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
193 + (__bridge CFStringRef)self,
194 + NULL,
195 + toEscape,
196 + kCFStringEncodingUTF8);
197 +}
198 +
199 +
200 +- (NSString *)URLEncodedParameterString {
201 + static CFStringRef toEscape = CFSTR(":/=,!$&'()*+;[]@#?%");
202 + return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
203 + (__bridge CFStringRef)self,
204 + NULL,
205 + toEscape,
206 + kCFStringEncodingUTF8);
207 +}
208 +
209 +
210 +- (NSString *)URLDecodedString {
211 + return (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault,
212 + (__bridge CFStringRef)self,
213 + CFSTR(""),
214 + kCFStringEncodingUTF8);
215 +}
216 +
217 +
218 +#pragma mark - Base64 Encoding
219 +
220 +- (NSString *)base64EncodedString {
221 + if ([self length] == 0) {
222 + return nil;
223 + }
224 +
225 + return [[self dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
226 +}
227 +
228 +
229 ++ (NSString *)stringWithBase64String:(NSString *)base64String {
230 + return [[NSString alloc] initWithData:[NSData dataWithBase64String:base64String] encoding:NSUTF8StringEncoding];
231 +}
232 +
233 +
234 +
235 +#pragma mark - Generating a UUID
236 +
237 ++ (NSString *)stringWithUUID {
238 + CFUUIDRef uuid = CFUUIDCreate(NULL);
239 + CFStringRef string = CFUUIDCreateString(NULL, uuid);
240 + CFRelease(uuid);
241 + return (__bridge_transfer NSString *)string;
242 +}
243 +
244 +
245 +#pragma mark - Trimming
246 +
247 +- (NSString *)stringByTrimmingLeadingAndTrailingCharactersInSet:(NSCharacterSet *)characterSet {
248 + return [[self stringByTrimmingLeadingCharactersInSet:characterSet]
249 + stringByTrimmingTrailingCharactersInSet:characterSet];
250 +}
251 +
252 +
253 +- (NSString *)stringByTrimmingLeadingAndTrailingWhitespaceAndNewlineCharacters {
254 + return [[self stringByTrimmingLeadingWhitespaceAndNewlineCharacters]
255 + stringByTrimmingTrailingWhitespaceAndNewlineCharacters];
256 +}
257 +
258 +
259 +- (NSString *)stringByTrimmingLeadingCharactersInSet:(NSCharacterSet *)characterSet {
260 + NSRange rangeOfFirstWantedCharacter = [self rangeOfCharacterFromSet:[characterSet invertedSet]];
261 + if (rangeOfFirstWantedCharacter.location == NSNotFound) {
262 + return @"";
263 + }
264 + return [self substringFromIndex:rangeOfFirstWantedCharacter.location];
265 +}
266 +
267 +
268 +- (NSString *)stringByTrimmingLeadingWhitespaceAndNewlineCharacters {
269 + return [self stringByTrimmingLeadingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
270 +}
271 +
272 +
273 +- (NSString *)stringByTrimmingTrailingCharactersInSet:(NSCharacterSet *)characterSet {
274 + NSRange rangeOfLastWantedCharacter = [self rangeOfCharacterFromSet:[characterSet invertedSet]
275 + options:NSBackwardsSearch];
276 + if (rangeOfLastWantedCharacter.location == NSNotFound) {
277 + return @"";
278 + }
279 + return [self substringToIndex:rangeOfLastWantedCharacter.location + 1]; // Non-inclusive
280 +}
281 +
282 +
283 +- (NSString *)stringByTrimmingTrailingWhitespaceAndNewlineCharacters {
284 + return [self stringByTrimmingTrailingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
285 +}
286 +
287 +@end
1 +/*
2 + Copyright 2010-2016 Warply Inc. All rights reserved.
3 +
4 + Redistribution and use in source and binary forms, without modification,
5 + are permitted provided that the following conditions are met:
6 +
7 + 1. Redistributions of source code must retain the above copyright notice, this
8 + list of conditions and the following disclaimer.
9 +
10 + 2. Redistributions in binaryform must reproduce the above copyright notice,
11 + this list of conditions and the following disclaimer in the documentation
12 + and/or other materials provided with the distribution.
13 +
14 + THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 + EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 + */
25 +
26 +#import <UIKit/UIKit.h>
27 +
28 +@interface UIViewController (WLAdditions)
29 +
30 +- (UIViewController *)topModalViewController;
31 +
32 +@end
1 +/*
2 + Copyright 2010-2016 Warply Inc. All rights reserved.
3 +
4 + Redistribution and use in source and binary forms, without modification,
5 + are permitted provided that the following conditions are met:
6 +
7 + 1. Redistributions of source code must retain the above copyright notice, this
8 + list of conditions and the following disclaimer.
9 +
10 + 2. Redistributions in binaryform must reproduce the above copyright notice,
11 + this list of conditions and the following disclaimer in the documentation
12 + and/or other materials provided with the distribution.
13 +
14 + THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 + EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 + */
25 +
26 +#import "UIViewController+WLAdditions.h"
27 +
28 +@implementation UIViewController (WLAdditions)
29 +
30 +#pragma mark - Public Methods
31 +///////////////////////////////////////////////////////////////////////////////
32 +- (UIViewController *)topModalViewController
33 +{
34 + return [self topModalViewControllerOfController:self];
35 +}
36 +
37 +#pragma mark - Private Methods
38 +///////////////////////////////////////////////////////////////////////////////
39 +- (UIViewController *)topModalViewControllerOfController:(UIViewController *)controller
40 +{
41 + UIViewController *presentedVC = [controller presentedViewController];
42 + if (presentedVC != nil)
43 + return [self topModalViewControllerOfController:presentedVC];
44 +
45 + return controller;
46 +}
47 +
48 +@end
1 +/*
2 + Copyright 2010-2016 Warply Inc. All rights reserved.
3 +
4 + Redistribution and use in source and binary forms, without modification,
5 + are permitted provided that the following conditions are met:
6 +
7 + 1. Redistributions of source code must retain the above copyright notice, this
8 + list of conditions and the following disclaimer.
9 +
10 + 2. Redistributions in binaryform must reproduce the above copyright notice,
11 + this list of conditions and the following disclaimer in the documentation
12 + and/or other materials provided with the distribution.
13 +
14 + THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 + EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 + */
25 +#import <Foundation/Foundation.h>
26 +#import <UIKit/UIKit.h>
27 +
28 +#import <UIKit/UIKit.h>
29 +
30 +#define IFPGA_NAMESTRING @"iFPGA"
31 +
32 +#define IPHONE_1_NAMESTRING @"iPhone 1"
33 +#define IPHONE_3G_NAMESTRING @"iPhone 3G"
34 +#define IPHONE_3GS_NAMESTRING @"iPhone 3GS"
35 +#define IPHONE_4_NAMESTRING @"iPhone 4"
36 +#define IPHONE_4S_NAMESTRING @"iPhone 4S"
37 +#define IPHONE_5_NAMESTRING @"iPhone 5"
38 +#define IPHONE_5C_NAMESTRING @"iPhone 5C"
39 +#define IPHONE_5S_NAMESTRING @"iPhone 5S"
40 +#define IPHONE_UNKNOWN_NAMESTRING @"Unknown iPhone"
41 +
42 +#define IPOD_1_NAMESTRING @"iPod touch 1"
43 +#define IPOD_2_NAMESTRING @"iPod touch 2"
44 +#define IPOD_3_NAMESTRING @"iPod touch 3"
45 +#define IPOD_4_NAMESTRING @"iPod touch 4"
46 +#define IPOD_5_NAMESTRING @"iPod touch 5"
47 +#define IPOD_UNKNOWN_NAMESTRING @"Unknown iPod"
48 +
49 +#define IPAD_1_NAMESTRING @"iPad 1"
50 +#define IPAD_2_NAMESTRING @"iPad 2"
51 +#define THE_NEW_IPAD_NAMESTRING @"The new iPad"
52 +#define IPAD_4G_NAMESTRING @"iPad 4G"
53 +#define IPAD_AIR_NAMESTRING @"iPad Air (WiFi)"
54 +#define IPAD_AIR_LTE_NAMESTRING @"iPad Air (LTE)"
55 +
56 +#define IPAD_MINI_NAMESTRING @"iPad mini"
57 +#define IPAD_UNKNOWN_NAMESTRING @"Unknown iPad"
58 +
59 +#define APPLETV_2G_NAMESTRING @"Apple TV 2"
60 +#define APPLETV_3G_NAMESTRING @"Apple TV 3"
61 +#define APPLETV_4G_NAMESTRING @"Apple TV 4"
62 +#define APPLETV_UNKNOWN_NAMESTRING @"Unknown Apple TV"
63 +
64 +#define IOS_FAMILY_UNKNOWN_DEVICE @"Unknown iOS device"
65 +
66 +#define IPHONE_SIMULATOR_NAMESTRING @"iPhone Simulator"
67 +#define IPHONE_SIMULATOR_IPHONE_NAMESTRING @"iPhone Simulator"
68 +#define IPHONE_SIMULATOR_IPAD_NAMESTRING @"iPad Simulator"
69 +#define SIMULATOR_APPLETV_NAMESTRING @"Apple TV Simulator"
70 +
71 +typedef enum {
72 + UIDeviceUnknown,
73 +
74 + UIDeviceiPhoneSimulator,
75 + UIDeviceiPhoneSimulatoriPhone, // both regular and iPhone 4 devices
76 + UIDeviceiPhoneSimulatoriPad,
77 + UIDeviceSimulatorAppleTV,
78 +
79 + UIDeviceiPhone1,
80 + UIDeviceiPhone3G,
81 + UIDeviceiPhone3GS,
82 + UIDeviceiPhone4,
83 + UIDeviceiPhone4GSM,
84 + UIDeviceiPhone4GSMRevA,
85 + UIDeviceiPhone4CDMA,
86 + UIDeviceiPhone4S,
87 + UIDeviceiPhone5,
88 + UIDeviceiPhone5GSM,
89 + UIDeviceiPhone5CDMA,
90 + UIDeviceiPhone5CGSM,
91 + UIDeviceiPhone5CGSMCDMA,
92 + UIDeviceiPhone5SGSM,
93 + UIDeviceiPhone5SGSMCDMA,
94 +
95 + UIDeviceiPod1,
96 + UIDeviceiPod2,
97 + UIDeviceiPod3,
98 + UIDeviceiPod4,
99 + UIDeviceiPod5,
100 +
101 + UIDeviceiPad1,
102 + UIDeviceiPad2,
103 + UIDeviceTheNewiPad,
104 + UIDeviceiPad4G,
105 + UIDeviceiPadAir,
106 + UIDeviceiPadAirLTE,
107 + UIDeviceiPadMini,
108 +
109 + UIDeviceAppleTV2,
110 + UIDeviceAppleTV3,
111 + UIDeviceAppleTV4,
112 +
113 + UIDeviceUnknowniPhone,
114 + UIDeviceUnknowniPod,
115 + UIDeviceUnknowniPad,
116 + UIDeviceUnknownAppleTV,
117 + UIDeviceIFPGA,
118 +
119 +} UIDevicePlatform;
120 +
121 +typedef enum {
122 + UIDeviceFamilyiPhone,
123 + UIDeviceFamilyiPod,
124 + UIDeviceFamilyiPad,
125 + UIDeviceFamilyAppleTV,
126 + UIDeviceFamilyUnknown,
127 +
128 +} UIDeviceFamily;
129 +
130 +@interface UIDevice (Hardware)
131 +- (NSString *)platform;
132 +- (NSString *)platformString;
133 +- (NSString *)deviceFamilyString;
134 +
135 +@end
136 +
137 +@interface WLKeychain : NSObject
138 +
139 ++ (BOOL)setString:(NSString *)string forKey:(NSString *)key;
140 ++ (NSString *)getStringForKey:(NSString *)key;
141 ++ (void)deleteStringForKey:(NSString *)key;
142 +
143 +@end
...\ No newline at end of file ...\ No newline at end of file
1 +/*
2 + Copyright 2010-2016 Warply Inc. All rights reserved.
3 +
4 + Redistribution and use in source and binary forms, without modification,
5 + are permitted provided that the following conditions are met:
6 +
7 + 1. Redistributions of source code must retain the above copyright notice, this
8 + list of conditions and the following disclaimer.
9 +
10 + 2. Redistributions in binaryform must reproduce the above copyright notice,
11 + this list of conditions and the following disclaimer in the documentation
12 + and/or other materials provided with the distribution.
13 +
14 + THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 + EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 + */
25 +
26 +#import "WLUtils.h"
27 +#import "WLGlobals.h"
28 +
29 +#import <Security/Security.h>
30 +
31 +#include <sys/socket.h> // Per msqr
32 +#include <sys/sysctl.h>
33 +#include <net/if.h>
34 +#include <net/if_dl.h>
35 +
36 +@implementation UIDevice (Hardware)
37 +/*
38 + Platforms
39 +
40 + iFPGA -> ??
41 +
42 + iPhone1,1 -> iPhone 1, M68
43 + iPhone1,2 -> iPhone 3G, N82
44 + iPhone2,1 -> iPhone 3GS, N88
45 + iPhone3,1 -> iPhone 4/GSM, N89
46 + iPhone3,2 -> iPhone 4/GSM Rev A, N90
47 + iPhone3,3 -> iPhone 4/CDMA, N92
48 + iPhone4,1 -> iPhone 4S/GSM+CDMA, N94
49 + iPhone5,1 -> iPhone 5/GSM, N41
50 + iPhone5,2 -> iPhone 5/GSM+CDMA, N42
51 + iPhone5,3 -> iPhone 5C/GSM, N48
52 + iPhone5,4 -> iPhone 5C/GSM+CDMA, N49
53 + iPhone6,1 -> iPhone 5S/GSM, N51
54 + iPhone6,2 -> iPhone 5S/GSM+CDMA, N53
55 +
56 + iPod1,1 -> iPod touch 1, N45
57 + iPod2,1 -> iPod touch 2, N72
58 + iPod2,2 -> iPod touch 3, Prototype
59 + iPod3,1 -> iPod touch 3, N18
60 + iPod4,1 -> iPod touch 4, N81
61 +
62 + // Thanks NSForge
63 + ipad0,1 -> iPad, Prototype
64 + iPad1,1 -> iPad 1, WiFi and 3G, K48
65 + iPad2,1 -> iPad 2, WiFi, K93
66 + iPad2,2 -> iPad 2, GSM 3G, K94
67 + iPad2,3 -> iPad 2, CDMA 3G, K95
68 + iPad2,4 -> iPad 2, WiFi R2, K93A
69 + iPad3,1 -> The new iPad, WiFi
70 + iPad3,2 -> The new iPad, CDMA
71 + iPad3,3 -> The new iPad
72 + iPad4,1 -> (iPad 4G, WiFi)
73 + iPad4,2 -> (iPad 4G, GSM)
74 + iPad4,3 -> (iPad 4G, CDMA)
75 +
76 + iProd2,1 -> AppleTV 2, Prototype
77 + AppleTV2,1 -> AppleTV 2, K66
78 + AppleTV3,1 -> AppleTV 3, ??
79 +
80 + i386, x86_64 -> iPhone Simulator
81 + */
82 +
83 +
84 +#pragma mark sysctlbyname utils
85 +////////////////////////////////////////////////////////////////////////////////
86 +- (NSString *) getSysInfoByName:(char *)typeSpecifier
87 +{
88 + size_t size;
89 + sysctlbyname(typeSpecifier, NULL, &size, NULL, 0);
90 +
91 + char *answer = malloc(size);
92 + sysctlbyname(typeSpecifier, answer, &size, NULL, 0);
93 +
94 + NSString *results = [NSString stringWithCString:answer encoding: NSUTF8StringEncoding];
95 +
96 + free(answer);
97 + return results;
98 +}
99 +////////////////////////////////////////////////////////////////////////////////
100 +- (NSString *) platform
101 +{
102 + return [self getSysInfoByName:"hw.machine"];
103 +}
104 +
105 +#pragma mark sysctl utils
106 +////////////////////////////////////////////////////////////////////////////////
107 +- (NSUInteger) getSysInfo: (uint) typeSpecifier
108 +{
109 + size_t size = sizeof(int);
110 + int results;
111 + int mib[2] = {CTL_HW, typeSpecifier};
112 + sysctl(mib, 2, &results, &size, NULL, 0);
113 + return (NSUInteger) results;
114 +}
115 +
116 +#pragma mark platform type and name utils
117 +////////////////////////////////////////////////////////////////////////////////
118 +- (NSUInteger) platformType
119 +{
120 + return [UIDevice platformTypeForString:[self platform]];
121 +}
122 +
123 +////////////////////////////////////////////////////////////////////////////////
124 +- (NSString *) platformString
125 +{
126 + return [UIDevice platformStringForType:[self platformType]];
127 +}
128 +
129 +////////////////////////////////////////////////////////////////////////////////
130 ++ (NSUInteger) platformTypeForString:(NSString *)platform
131 +{
132 + // The ever mysterious iFPGA
133 + if ([platform isEqualToString:@"iFPGA"]) return UIDeviceIFPGA;
134 +
135 + // iPhone
136 + if ([platform isEqualToString:@"iPhone1,1"]) return UIDeviceiPhone1;
137 + if ([platform isEqualToString:@"iPhone1,2"]) return UIDeviceiPhone3G;
138 + if ([platform hasPrefix:@"iPhone2"]) return UIDeviceiPhone3GS;
139 + if ([platform isEqualToString:@"iPhone3,1"]) return UIDeviceiPhone4GSM;
140 + if ([platform isEqualToString:@"iPhone3,2"]) return UIDeviceiPhone4GSMRevA;
141 + if ([platform isEqualToString:@"iPhone3,3"]) return UIDeviceiPhone4CDMA;
142 + if ([platform hasPrefix:@"iPhone4"]) return UIDeviceiPhone4S;
143 + if ([platform isEqualToString:@"iPhone5,1"]) return UIDeviceiPhone5GSM;
144 + if ([platform isEqualToString:@"iPhone5,2"]) return UIDeviceiPhone5CDMA;
145 + if ([platform isEqualToString:@"iPhone5,3"]) return UIDeviceiPhone5CGSM;
146 + if ([platform isEqualToString:@"iPhone5,4"]) return UIDeviceiPhone5CGSMCDMA;
147 + if ([platform isEqualToString:@"iPhone6,1"]) return UIDeviceiPhone5SGSM;
148 + if ([platform isEqualToString:@"iPhone6,2"]) return UIDeviceiPhone5SGSMCDMA;
149 +
150 + // iPod
151 + if ([platform hasPrefix:@"iPod1"]) return UIDeviceiPod1;
152 + if ([platform isEqualToString:@"iPod2,2"]) return UIDeviceiPod3;
153 + if ([platform hasPrefix:@"iPod2"]) return UIDeviceiPod2;
154 + if ([platform hasPrefix:@"iPod3"]) return UIDeviceiPod3;
155 + if ([platform hasPrefix:@"iPod4"]) return UIDeviceiPod4;
156 + if ([platform hasPrefix:@"iPod5"]) return UIDeviceiPod5;
157 +
158 + // iPad
159 + if ([platform hasPrefix:@"iPad1"]) return UIDeviceiPad1;
160 + if ([platform hasPrefix:@"iPad2"])
161 + {
162 + NSInteger submodel = [ UIDevice getSubmodel:platform ];
163 + if ( submodel <= 4 )
164 + {
165 + return UIDeviceiPad2;
166 + } else
167 + {
168 + return UIDeviceiPadMini;
169 + }
170 + }
171 + if ([platform hasPrefix:@"iPad3"])
172 + {
173 + NSInteger submodel = [ UIDevice getSubmodel:platform ];
174 + if ( submodel <= 3 )
175 + {
176 + return UIDeviceTheNewiPad;
177 + } else
178 + {
179 + return UIDeviceiPad4G;
180 + }
181 + }
182 +
183 + if ([platform isEqualToString:@"iPad4,1"]) return UIDeviceiPadAir;
184 + if ([platform isEqualToString:@"iPad4,2"]) return UIDeviceiPadAirLTE;
185 +
186 + // Apple TV
187 + if ([platform hasPrefix:@"AppleTV2"]) return UIDeviceAppleTV2;
188 + if ([platform hasPrefix:@"AppleTV3"]) return UIDeviceAppleTV3;
189 +
190 + if ([platform hasPrefix:@"iPhone"]) return UIDeviceUnknowniPhone;
191 + if ([platform hasPrefix:@"iPod"]) return UIDeviceUnknowniPod;
192 + if ([platform hasPrefix:@"iPad"]) return UIDeviceUnknowniPad;
193 + if ([platform hasPrefix:@"AppleTV"]) return UIDeviceUnknownAppleTV;
194 +
195 + // Simulator thanks Jordan Breeding
196 + if ([platform hasSuffix:@"86"] || [platform isEqual:@"x86_64"])
197 + {
198 + BOOL smallerScreen = [[UIScreen mainScreen] bounds].size.width < 768;
199 + return smallerScreen ? UIDeviceiPhoneSimulatoriPhone : UIDeviceiPhoneSimulatoriPad;
200 + }
201 +
202 + return UIDeviceUnknown;
203 +}
204 +
205 +////////////////////////////////////////////////////////////////////////////////
206 ++( NSInteger )getSubmodel:( NSString* )platform
207 +{
208 + NSInteger submodel = -1;
209 +
210 + NSArray* components = [ platform componentsSeparatedByString:@"," ];
211 + if ( [ components count ] >= 2 )
212 + {
213 + submodel = [ [ components objectAtIndex:1 ] intValue ];
214 + }
215 + return submodel;
216 +}
217 +
218 +////////////////////////////////////////////////////////////////////////////////
219 ++ (NSString *) platformStringForType:(NSUInteger)platformType
220 +{
221 + switch (platformType)
222 + {
223 + case UIDeviceiPhone1: return IPHONE_1_NAMESTRING;
224 + case UIDeviceiPhone3G: return IPHONE_3G_NAMESTRING;
225 + case UIDeviceiPhone3GS: return IPHONE_3GS_NAMESTRING;
226 + case UIDeviceiPhone4GSM: return IPHONE_4_NAMESTRING;
227 + case UIDeviceiPhone4GSMRevA: return IPHONE_4_NAMESTRING;
228 + case UIDeviceiPhone4CDMA: return IPHONE_4_NAMESTRING;
229 + case UIDeviceiPhone4S: return IPHONE_4S_NAMESTRING;
230 + case UIDeviceiPhone5GSM: return IPHONE_5_NAMESTRING;
231 + case UIDeviceiPhone5CDMA: return IPHONE_5_NAMESTRING;
232 + case UIDeviceiPhone5CGSM: return IPHONE_5C_NAMESTRING;
233 + case UIDeviceiPhone5CGSMCDMA: return IPHONE_5C_NAMESTRING;
234 + case UIDeviceiPhone5SGSM: return IPHONE_5S_NAMESTRING;
235 + case UIDeviceiPhone5SGSMCDMA: return IPHONE_5S_NAMESTRING;
236 + case UIDeviceUnknowniPhone: return IPHONE_UNKNOWN_NAMESTRING;
237 +
238 + case UIDeviceiPod1: return IPOD_1_NAMESTRING;
239 + case UIDeviceiPod2: return IPOD_2_NAMESTRING;
240 + case UIDeviceiPod3: return IPOD_3_NAMESTRING;
241 + case UIDeviceiPod4: return IPOD_4_NAMESTRING;
242 + case UIDeviceiPod5: return IPOD_5_NAMESTRING;
243 + case UIDeviceUnknowniPod: return IPOD_UNKNOWN_NAMESTRING;
244 +
245 + case UIDeviceiPad1 : return IPAD_1_NAMESTRING;
246 + case UIDeviceiPad2 : return IPAD_2_NAMESTRING;
247 + case UIDeviceTheNewiPad : return THE_NEW_IPAD_NAMESTRING;
248 + case UIDeviceiPad4G : return IPAD_4G_NAMESTRING;
249 + case UIDeviceiPadAir : return IPAD_AIR_NAMESTRING;
250 + case UIDeviceiPadAirLTE : return IPAD_AIR_LTE_NAMESTRING;
251 + case UIDeviceiPadMini : return IPAD_MINI_NAMESTRING;
252 + case UIDeviceUnknowniPad : return IPAD_UNKNOWN_NAMESTRING;
253 +
254 + case UIDeviceAppleTV2 : return APPLETV_2G_NAMESTRING;
255 + case UIDeviceAppleTV3 : return APPLETV_3G_NAMESTRING;
256 + case UIDeviceAppleTV4 : return APPLETV_4G_NAMESTRING;
257 + case UIDeviceUnknownAppleTV: return APPLETV_UNKNOWN_NAMESTRING;
258 +
259 + case UIDeviceiPhoneSimulator: return IPHONE_SIMULATOR_NAMESTRING;
260 + case UIDeviceiPhoneSimulatoriPhone: return IPHONE_SIMULATOR_IPHONE_NAMESTRING;
261 + case UIDeviceiPhoneSimulatoriPad: return IPHONE_SIMULATOR_IPAD_NAMESTRING;
262 + case UIDeviceSimulatorAppleTV: return SIMULATOR_APPLETV_NAMESTRING;
263 +
264 + case UIDeviceIFPGA: return IFPGA_NAMESTRING;
265 +
266 + default: return IOS_FAMILY_UNKNOWN_DEVICE;
267 + }
268 +}
269 +
270 +////////////////////////////////////////////////////////////////////////////////
271 ++ (NSString *) platformStringForPlatform:(NSString *)platform
272 +{
273 + NSUInteger platformType = [UIDevice platformTypeForString:platform];
274 + return [UIDevice platformStringForType:platformType];
275 +}
276 +
277 +////////////////////////////////////////////////////////////////////////////////
278 +- (UIDeviceFamily) deviceFamily
279 +{
280 + NSString *platform = [self platform];
281 + if ([platform hasPrefix:@"iPhone"]) return UIDeviceFamilyiPhone;
282 + if ([platform hasPrefix:@"iPod"]) return UIDeviceFamilyiPod;
283 + if ([platform hasPrefix:@"iPad"]) return UIDeviceFamilyiPad;
284 + if ([platform hasPrefix:@"AppleTV"]) return UIDeviceFamilyAppleTV;
285 +
286 + return UIDeviceFamilyUnknown;
287 +}
288 +
289 +////////////////////////////////////////////////////////////////////////////////
290 +- (NSString *)deviceFamilyString
291 +{
292 + NSString *platform = [self platform];
293 + if ([platform hasPrefix:@"iPhone"])
294 + return @"iPhone";
295 + if ([platform hasPrefix:@"iPod"])
296 + return @"iPod";
297 + if ([platform hasPrefix:@"iPad"])
298 + return @"iPad";
299 + if ([platform hasPrefix:@"AppleTV"])
300 + return @"AppleTV";
301 + return @"Unknown";
302 +}
303 +
304 +@end
305 +
306 +@implementation WLKeychain
307 +
308 +////////////////////////////////////////////////////////////////////////////////
309 ++ (NSString *)appName
310 +{
311 + NSBundle *bundle = [NSBundle bundleForClass:[self class]];
312 +
313 + // Attempt to find a name for this application
314 + NSString *appName = [bundle objectForInfoDictionaryKey:@"CFBundleDisplayName"];
315 + if (appName != nil)
316 + appName = [bundle objectForInfoDictionaryKey:@"CFBundleName"];
317 +
318 + return appName;
319 +}
320 +
321 +////////////////////////////////////////////////////////////////////////////////
322 ++ (NSString *)bundleIdentifier
323 +{
324 + return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleIdentifier"];
325 +}
326 +
327 +////////////////////////////////////////////////////////////////////////////////
328 ++ (BOOL)setString:(NSString *)string forKey:(NSString *)key
329 +{
330 + if (string == nil || key == nil)
331 + return NO;
332 +
333 + key = [NSString stringWithFormat:@"%@.%@", [WLKeychain bundleIdentifier], key];
334 +
335 + // First check if it already exists, by creating a search dictionary and requesting that
336 + // nothing be returned, and performing the search anyway.
337 + NSMutableDictionary *existsQueryDictionary = [NSMutableDictionary dictionary];
338 +
339 + NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
340 + [existsQueryDictionary setObject:(__bridge id)(kSecClassGenericPassword) forKey:(__bridge id)(kSecClass)];
341 +
342 + // Add the keys to the search dict
343 + [existsQueryDictionary setObject:key forKey:(__bridge id)(kSecAttrAccount)];
344 + [existsQueryDictionary setObject:@"service" forKey:(__bridge id)(kSecAttrService)];
345 + [existsQueryDictionary setObject:(__bridge id)(kSecAttrAccessibleWhenUnlocked) forKey:(__bridge id)(kSecAttrAccessible)];
346 +
347 + OSStatus res = SecItemCopyMatching((__bridge CFDictionaryRef)(existsQueryDictionary), NULL);
348 + if (res == errSecItemNotFound) {
349 + if (string != nil) {
350 + NSMutableDictionary *addDict = existsQueryDictionary;
351 + [addDict setObject:data forKey:(__bridge id)(kSecValueData)];
352 +
353 + res = SecItemAdd((__bridge CFDictionaryRef)(addDict), NULL);
354 + NSAssert1(res == errSecSuccess, @"Received %d from SecItemAdd!", (int)res);
355 + }
356 + }
357 + else if (res == errSecSuccess) {
358 + // Modify an existing one
359 + // Actually pull it now of the keychain at this point.
360 + NSDictionary *attributeDict = [NSDictionary dictionaryWithObject:data forKey:(__bridge id)(kSecValueData)];
361 +
362 + res = SecItemUpdate((__bridge CFDictionaryRef)(existsQueryDictionary), (__bridge CFDictionaryRef)(attributeDict));
363 + NSAssert1(res == errSecSuccess, @"SecItemUpdated returned %d!", (int)res);
364 +
365 + }
366 + else
367 + NSAssert1(NO, @"Received %d from SecItemCopyMatching!", (int)res);
368 +
369 + return YES;
370 +}
371 +
372 +////////////////////////////////////////////////////////////////////////////////
373 ++ (NSString*)getStringForKey:(NSString *)key
374 +{
375 + key = [NSString stringWithFormat:@"%@.%@", [WLKeychain bundleIdentifier], key];
376 +
377 + NSMutableDictionary *existsQueryDictionary = [NSMutableDictionary dictionary];
378 + [existsQueryDictionary setObject:(id)CFBridgingRelease(kSecClassGenericPassword) forKey:(id)CFBridgingRelease(kSecClass)];
379 +
380 + // Add the keys to the search dict
381 + [existsQueryDictionary setObject:@"service" forKey:(id)CFBridgingRelease(kSecAttrService)];
382 + [existsQueryDictionary setObject:key forKey:(id)CFBridgingRelease(kSecAttrAccount)];
383 + [existsQueryDictionary setObject:(id)CFBridgingRelease(kSecAttrAccessibleWhenUnlocked) forKey:(id)CFBridgingRelease(kSecAttrAccessible)];
384 +
385 + // We want the data back!
386 + NSData *data = nil;
387 + [existsQueryDictionary setObject:(id)kCFBooleanTrue forKey:(__bridge id)(kSecReturnData)];
388 +
389 + OSStatus res = SecItemCopyMatching((__bridge CFDictionaryRef)(existsQueryDictionary), (CFTypeRef *)(void *)&data);
390 +
391 + if (res == errSecSuccess) {
392 + NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
393 + return string;
394 + }
395 + else
396 + NSAssert1(res == errSecItemNotFound, @"SecItemCopyMatching returned %d!", (int)res);
397 +
398 + return nil;
399 +}
400 +
401 +////////////////////////////////////////////////////////////////////////////////
402 ++ (void)deleteStringForKey:(NSString *)key
403 +{
404 + key = [NSString stringWithFormat:@"%@.%@", [WLKeychain bundleIdentifier], key];
405 +
406 + NSMutableDictionary *existsQueryDictionary = [NSMutableDictionary dictionary];
407 + [existsQueryDictionary setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass];
408 +
409 + // Add the keys to the search dict
410 + [existsQueryDictionary setObject:@"service" forKey:(__bridge id)kSecAttrService];
411 + [existsQueryDictionary setObject:key forKey:(__bridge id)kSecAttrAccount];
412 + [existsQueryDictionary setObject:(__bridge id)kSecAttrAccessibleWhenUnlocked forKey:(__bridge id)kSecAttrAccessible];
413 +
414 + SecItemDelete((__bridge CFDictionaryRef)existsQueryDictionary);
415 +}
416 +
417 +@end
...\ No newline at end of file ...\ No newline at end of file
1 +/*
2 + Copyright 2010-2016 Warply Inc. All rights reserved.
3 +
4 + Redistribution and use in source and binary forms, without modification,
5 + are permitted provided that the following conditions are met:
6 +
7 + 1. Redistributions of source code must retain the above copyright notice, this
8 + list of conditions and the following disclaimer.
9 +
10 + 2. Redistributions in binaryform must reproduce the above copyright notice,
11 + this list of conditions and the following disclaimer in the documentation
12 + and/or other materials provided with the distribution.
13 +
14 + THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 + EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 + */
25 +
26 +/*!
27 + @header WLAPSItem.h
28 + The WLAPSItem object is used to model the parameters of the received Remote
29 + Notification (Push) on how to notify user, in a structured way.
30 + @copyright Warply Inc.
31 + */
32 +#import <Foundation/Foundation.h>
33 +
34 +/*!
35 + @class WLAPSItem
36 + @discussion This object contains the parameters for the received Remote Notification
37 + (Push), on how to notify the user, such as badge number and both alert text and sound.
38 + */
39 +@interface WLAPSItem : NSObject
40 +{
41 +@private
42 + NSUInteger _badge;
43 + NSString *_alert;
44 + NSString *_sound;
45 +}
46 +/*!
47 + @property badge
48 + @abstract The number that will be shown as notification badge.
49 + */
50 +@property (nonatomic) NSUInteger badge;
51 +/*!
52 + @property alert
53 + @abstract A string object of the alert text
54 + */
55 +@property (nonatomic, copy) NSString *alert;
56 +/*!
57 + @property sound
58 + @abstract A string object of the file for the alert sound.
59 + */
60 +@property (nonatomic, copy) NSString *sound;
61 +
62 +/*!
63 + @methodgroup Initializing a WLAPSItem Object
64 + */
65 +/*!
66 + @abstract Initialise a WLAPSItem object.
67 + @discussion Initializes and returns a newly allocated WLAPSItem object with the specified
68 + attributes.
69 + @param attributes A dictionary object which contains remote notification attributes.
70 + @return Returns WLAPSItem object.
71 + */
72 +- (id)initWithAttributes:(NSDictionary *)attributes;
73 +
74 +@end
1 +/*
2 + Copyright 2010-2016 Warply Inc. All rights reserved.
3 +
4 + Redistribution and use in source and binary forms, without modification,
5 + are permitted provided that the following conditions are met:
6 +
7 + 1. Redistributions of source code must retain the above copyright notice, this
8 + list of conditions and the following disclaimer.
9 +
10 + 2. Redistributions in binaryform must reproduce the above copyright notice,
11 + this list of conditions and the following disclaimer in the documentation
12 + and/or other materials provided with the distribution.
13 +
14 + THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 + EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 + */
25 +
26 +#import "WLAPSItem.h"
27 +#import "WLGlobals.h"
28 +
29 +@implementation WLAPSItem
30 +
31 +@synthesize badge = _badge;
32 +@synthesize alert = _alert;
33 +@synthesize sound = _sound;
34 +
35 +#pragma mark - Initialization
36 +///////////////////////////////////////////////////////////////////////////////
37 +- (id)initWithAttributes:(NSDictionary *)attributes
38 +{
39 + self = [super init];
40 + if (self) {
41 + NSObject *idx = nil;
42 + for (NSString *key in [attributes allKeys]) {
43 + idx = [attributes objectForKey:key];
44 + @try {
45 + if ([idx isKindOfClass:[NSNull class]] )
46 + continue;
47 +
48 + [self setValue:idx forKey:key];
49 + }
50 + @catch (NSException *e) { WLLOG(@"%@: UnKnown Key:%@ - Value:%@", [e name], key, idx); }
51 + @finally { }
52 + }
53 + }
54 +
55 + return self;
56 +}
57 +
58 +@end
1 +/*
2 + Copyright 2010-2016 Warply Inc. All rights reserved.
3 +
4 + Redistribution and use in source and binary forms, without modification,
5 + are permitted provided that the following conditions are met:
6 +
7 + 1. Redistributions of source code must retain the above copyright notice, this
8 + list of conditions and the following disclaimer.
9 +
10 + 2. Redistributions in binaryform must reproduce the above copyright notice,
11 + this list of conditions and the following disclaimer in the documentation
12 + and/or other materials provided with the distribution.
13 +
14 + THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 + EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 + */
25 +
26 +/*!
27 + @header WLBaseItem.h
28 + The WLAPSItem object is used to model the attributes for the received Remote
29 + Notification (Push) in a structured way.
30 + @copyright Warply Inc.
31 + */
32 +#import <Foundation/Foundation.h>
33 +#import "WLAPSItem.h"
34 +
35 +/*!
36 + @class WLBaseItem
37 + @discussion This object contains the attributes for the received Remote Notification
38 + (Push) such as message, custom data, action etc.
39 + */
40 +@interface WLBaseItem : NSObject
41 +{
42 +@private
43 + NSInteger _action;
44 + NSString *_session_uuid;
45 + NSString *_trace;
46 + NSString *_message;
47 + WLAPSItem *_apsItem;
48 + NSDictionary *_customData;
49 +}
50 +/*!
51 + @property action
52 + @abstract An integer id for the action need to be executed for the received
53 + remote notification (push).
54 + */
55 +@property (nonatomic) NSInteger action;
56 +/*!
57 + @property openedCount
58 + @abstract An integer counter of the times the offer html has been loaded by the user.
59 + */
60 +@property (nonatomic) NSInteger openedCount;
61 +/*!
62 + @property session_uuid
63 + @abstract A string object with unique identification of the received remote
64 + notification (push).
65 + */
66 +@property (nonatomic, copy) NSString *session_uuid;
67 +/*!
68 + @property trace
69 + @abstract A string object with a tracing identification of the received remote
70 + notification (push).
71 + */
72 +@property (nonatomic, copy) NSString *trace;
73 +/*!
74 + @property message
75 + @abstract A string object with a message of the received remote notification
76 + (push).
77 + */
78 +@property (nonatomic, copy) NSString *message;
79 +/*!
80 + @property apsItem
81 + @abstract A WLAPSItem object with a user notification parameters of the
82 + received remote notification (push).
83 + @seealso //apple_ref/occ/cl/WLAPSItem WLAPSItem
84 + */
85 +@property (nonatomic, strong) WLAPSItem *apsItem;
86 +/*!
87 + @property customData
88 + @abstract A dictionary object with key-value arbitrary data contained inside the
89 + received remote notification (push).
90 + */
91 +@property (nonatomic, strong) NSDictionary *customData;
92 +
93 +/*!
94 + @methodgroup Initializing a WLBaseItem Object
95 + */
96 +/*!
97 + @abstract Initialise a WLBaseItem Object.
98 + @discussion Initializes and returns a newly allocated WLAPSItem object with the
99 + specified attributes.
100 + @param attributes A dictionary object which contains remote notification attributes.
101 + @return Returns WLBaseItem object.
102 + */
103 +- (id)initWithAttributes:(NSDictionary *)attributes;
104 +
105 +/*!
106 + @methodgroup Getting WLBaseItem URLs
107 + */
108 +/*!
109 + @abstract Get Remote Notification (Push) page url.
110 + @discussion Returns the url for the web page of the offer related to the received
111 + Remote Notification (push).
112 + @return Returns a string object with offer web page url.
113 + */
114 +- (NSString *)getPageURL;
115 +/*!
116 + @abstract Get Remote Notification (Push) image url.
117 + @discussion Returns the url for the placeholder image of the offer related to the
118 + received Remote Notification (push).
119 + @return Returns a string object with the offer placeholder url.
120 + */
121 +- (NSString *)getImageURL;
122 +
123 +@end
1 +/*
2 + Copyright 2010-2016 Warply Inc. All rights reserved.
3 +
4 + Redistribution and use in source and binary forms, without modification,
5 + are permitted provided that the following conditions are met:
6 +
7 + 1. Redistributions of source code must retain the above copyright notice, this
8 + list of conditions and the following disclaimer.
9 +
10 + 2. Redistributions in binaryform must reproduce the above copyright notice,
11 + this list of conditions and the following disclaimer in the documentation
12 + and/or other materials provided with the distribution.
13 +
14 + THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 + EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 + */
25 +
26 +#import "WLBaseItem.h"
27 +#import "WLGlobals.h"
28 +
29 +#import "Warply.h"
30 +
31 +@implementation WLBaseItem
32 +
33 +@synthesize action = _action;
34 +@synthesize session_uuid = _session_uuid;
35 +@synthesize trace = _trace;
36 +@synthesize message = _message;
37 +@synthesize apsItem = _apsItem;
38 +@synthesize customData = _customData;
39 +
40 +#pragma mark - Initialization
41 +///////////////////////////////////////////////////////////////////////////////
42 +- (id)initWithAttributes:(NSDictionary *)attributes
43 +{
44 + self = [super init];
45 + if (self) {
46 + self.customData = [NSMutableDictionary dictionary];
47 + NSObject *idx = nil;
48 + for (NSString *key in [attributes allKeys]) {
49 + idx = [attributes objectForKey:key];
50 + @try {
51 + if ([idx isKindOfClass:[NSNull class]] )
52 + continue;
53 +
54 + if ([key isEqualToString:@"_a"])
55 + [self setValue:idx forKey:@"action"];
56 + else if ([key isEqualToString:@"aps"])
57 + _apsItem = [[WLAPSItem alloc] initWithAttributes:(NSDictionary*)idx];
58 + else
59 + [self setValue:idx forKey:key];
60 + }
61 + @catch (NSException *e) {
62 + [_customData setValue:idx forKey:key];
63 + WLLOG(@"%@: UnKnown Key:%@ - Value:%@", [e name], key, idx); }
64 + @finally { }
65 + }
66 + }
67 +
68 + return self;
69 +}
70 +
71 +#pragma mark - Properties
72 +///////////////////////////////////////////////////////////////////////////////
73 +- (NSString*)message
74 +{
75 + if (_apsItem != nil)
76 + return _apsItem.alert;
77 +
78 + return _message;
79 +}
80 +
81 +#pragma mark - Public Methods
82 +///////////////////////////////////////////////////////////////////////////////
83 +- (NSString *)getPageURL
84 +{
85 + return [NSString stringWithFormat:WARP_PAGE_URL_FORMAT, [[Warply sharedService] baseURL], _session_uuid];
86 +}
87 +
88 +///////////////////////////////////////////////////////////////////////////////
89 +- (NSString *)getImageURL
90 +{
91 + return [NSString stringWithFormat:WARP_IMAGE_URL_FORMAT, [[Warply sharedService] baseURL], _session_uuid];
92 +}
93 +
94 +@end
95 +
1 +/*
2 + Copyright 2010-2016 Warply Inc. All rights reserved.
3 +
4 + Redistribution and use in source and binary forms, without modification,
5 + are permitted provided that the following conditions are met:
6 +
7 + 1. Redistributions of source code must retain the above copyright notice, this
8 + list of conditions and the following disclaimer.
9 +
10 + 2. Redistributions in binaryform must reproduce the above copyright notice,
11 + this list of conditions and the following disclaimer in the documentation
12 + and/or other materials provided with the distribution.
13 +
14 + THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 + EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 + */
25 +
26 +/*!
27 + @header WLBeacon.h
28 + The WLBeacon object is used to model the parameters of the iBeacon device
29 + that the Service is going to monitor
30 + @copyright Warply Inc.
31 + */
32 +
33 +#import <Foundation/Foundation.h>
34 +
35 +/*!
36 + @class WLBeacon
37 + @discussion This object contains the parameters for the iBeacon device
38 + that the WLBeaconManager will monitor.
39 + */
40 +@interface WLBeacon : NSObject
41 +
42 +/*!
43 + @property beaconIdentifier
44 + @abstract A string identifier for an iBeacon device.
45 + */
46 +@property(nonatomic, copy) NSString *beaconIdentifier;
47 +/*!
48 + @property beaconUUID
49 + @abstract The UUID string that is bounded with an iBeacon device.
50 + */
51 +@property(nonatomic, strong) NSUUID *beaconUUID;
52 +
53 +/*!
54 + @methodgroup Initializing a WLBeacon Object
55 + */
56 +/*!
57 + @abstract Initialise a WLBeacon object.
58 + @discussion Initializes and returns a newly allocated WLBeacon object with the specified
59 + attributes.
60 + @param uuid A string that contains the UUID of the iBeacon device.
61 + @param identifier A string identifier that characterizes the iBeacon device.
62 + @return Returns WLBeacon object.
63 + */
64 +- (instancetype)initWithUUID:(NSString*)uuid identifier:(NSString*)identifier;
65 +@end
1 +//
2 +// WLBeaconRegion.m
3 +// DemoApp
4 +//
5 +// Created by Sergey Korobyin on 09.06.15.
6 +// Copyright (c) 2015 YC. All rights reserved.
7 +//
8 +
9 +#import "WLBeacon.h"
10 +
11 +@implementation WLBeacon
12 +
13 +- (instancetype)initWithUUID:(NSString*)uuid identifier:(NSString*)identifier{
14 + if (self = [super init]) {
15 + _beaconUUID = [[NSUUID alloc] initWithUUIDString:uuid];
16 + _beaconIdentifier = identifier;
17 + }
18 +
19 + return self;
20 +}
21 +
22 +
23 +
24 +@end
1 +/*
2 + Copyright 2010-2016 Warply Inc. All rights reserved.
3 +
4 + Redistribution and use in source and binary forms, without modification,
5 + are permitted provided that the following conditions are met:
6 +
7 + 1. Redistributions of source code must retain the above copyright notice, this
8 + list of conditions and the following disclaimer.
9 +
10 + 2. Redistributions in binaryform must reproduce the above copyright notice,
11 + this list of conditions and the following disclaimer in the documentation
12 + and/or other materials provided with the distribution.
13 +
14 + THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 + EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 + */
25 +
26 +/*!
27 + @header WLInboxItem.h
28 + The WLInboxItem object is used to model the information related to the offer for
29 + which the Remote Notification (Push) was sent.
30 + @copyright Warply Inc.
31 + */
32 +#import <Foundation/Foundation.h>
33 +#import "WLBaseItem.h"
34 +#import <CoreLocation/CoreLocation.h>
35 +
36 +/*!
37 + @class WLInboxItem
38 + @discussion This object contains the information related to the offer for
39 + which the Remote Notification (Push) was sent, such as: offer title and subtitle,
40 + offer message, offer category, expiration date etc.
41 + */
42 +@interface WLInboxItem : WLBaseItem
43 +
44 +/*!
45 + @property title
46 + @abstract An string object with the offer title.
47 + */
48 +@property (nonatomic, copy) NSString *title;
49 +/*!
50 + @property subtitle
51 + @abstract An string object with the offer subtitle.
52 + */
53 +@property (nonatomic, copy) NSString *subtitle;
54 +/*!
55 + @property offer_message
56 + @abstract An string object with the offer message.
57 + */
58 +@property (nonatomic, copy) NSString *offer_message;
59 +/*!
60 + @property offer_category
61 + @abstract An string object with the offer category.
62 + */
63 +@property (nonatomic, copy) NSString *offer_category;
64 +/*!
65 + @property expires
66 + @abstract An integer object with the offer expiration date (epoch format).
67 + */
68 +@property(nonatomic) NSInteger expires;
69 +/*!
70 + @property starts
71 + @abstract An integer object with the offer starting date (epoch format).
72 + */
73 +@property(nonatomic) NSInteger starts;
74 +/*!
75 + @property delivered
76 + @abstract An integer with the time / date the offer was delivered (epoch format).
77 + */
78 +@property (nonatomic) NSInteger delivered;
79 +
80 +@property (nonatomic) NSString *extra_fields;
81 +
82 +/*!
83 + @property opened
84 + @abstract An integer counting the times this offer has been opened.
85 + */
86 +@property (nonatomic) NSInteger opened;
87 +
88 +/*!
89 + @property sorting
90 + @abstract An NSNumber wrapping an int indicating the suggested order of the offers from the server in descending order.
91 + */
92 +@property (nonatomic) NSInteger sorting;
93 +
94 +/*!
95 + @property is_new
96 + @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
97 + */
98 +@property (nonatomic) BOOL is_new;
99 +
100 +/*!
101 + @property location
102 + @abstract This property is a CLLocation object if the inbox item is connected to a geofencing poi and nil otherwise
103 + */
104 +@property (nonatomic) CLLocation *location;
105 +
106 +/*!
107 + @property distance
108 + @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.
109 + */
110 +@property (nonatomic) CLLocationDistance distance;
111 +
112 +/*!
113 + @property radius
114 + @abstract The radius of the corresponding geofence.
115 + @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.
116 + */
117 +@property (nonatomic) CLLocationDistance radius;
118 +
119 +/*!
120 + @property name
121 + @abstract The alias of the item in case it is linked to a location (location != nil).
122 + @see //apple_ref/occ/instp/WLInboxItem/location location
123 + */
124 +@property (nonatomic) NSString *name;
125 +/**
126 + * @property display_type
127 + @abstract This property defines the type of the native ad.
128 + @discussion It can be full_page, half_page, list or feed.
129 + */
130 +@property (nonatomic) NSString *display_type;
131 +/*!
132 + @property campaign_type
133 + @abstract This property defines the type of the campaign.
134 + @discussion It can be standard-offer, beacon, etc.
135 + */
136 +@property (nonatomic) NSString *campaign_type;
137 +
138 +/*!
139 + @methodgroup Initializing a WLInboxItem Object
140 + */
141 +/*!
142 + @abstract Initialise a WLInboxItem Object.
143 + @discussion Initializes and returns a newly allocated WLInboxItem object with
144 + the specified WLBaseItem object.
145 + @param baseItem A WLBaseItem object.
146 + @return Returns WLInboxItem object.
147 + @see //apple_ref/occ/cl/WLBaseItem WLBaseItem
148 + */
149 +- (id)initWithItem:(WLBaseItem *)baseItem;
150 +
151 +@end
1 +/*
2 + Copyright 2010-2016 Warply Inc. All rights reserved.
3 +
4 + Redistribution and use in source and binary forms, without modification,
5 + are permitted provided that the following conditions are met:
6 +
7 + 1. Redistributions of source code must retain the above copyright notice, this
8 + list of conditions and the following disclaimer.
9 +
10 + 2. Redistributions in binaryform must reproduce the above copyright notice,
11 + this list of conditions and the following disclaimer in the documentation
12 + and/or other materials provided with the distribution.
13 +
14 + THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 + EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 + */
25 +
26 +#import "WLInboxItem.h"
27 +#import "WLGlobals.h"
28 +
29 +#import "Warply.h"
30 +#import "WLBaseItem.h"
31 +
32 +@implementation WLInboxItem
33 +
34 +#pragma mark - Initialization
35 +///////////////////////////////////////////////////////////////////////////////
36 +- (id)initWithItem:(WLBaseItem *)baseItem
37 +{
38 + self = [super init];
39 + if (self) {
40 + self.action = baseItem.action;
41 + self.session_uuid = baseItem.session_uuid;
42 + self.trace = baseItem.trace;
43 + self.message = baseItem.message;
44 + self.apsItem = baseItem.apsItem;
45 + }
46 +
47 + return self;
48 +}
49 +
50 +@end
1 +/*
2 + Copyright 2010-2016 Warply Inc. All rights reserved.
3 +
4 + Redistribution and use in source and binary forms, without modification,
5 + are permitted provided that the following conditions are met:
6 +
7 + 1. Redistributions of source code must retain the above copyright notice, this
8 + list of conditions and the following disclaimer.
9 +
10 + 2. Redistributions in binaryform must reproduce the above copyright notice,
11 + this list of conditions and the following disclaimer in the documentation
12 + and/or other materials provided with the distribution.
13 +
14 + THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 + EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 + */
25 +
26 +/*!
27 + @header WLInboxItemViewController.h
28 + The WLInboxItemViewController is a UIWebViewController that shows modally the
29 + web page of the selected offer (WLInboxItem).
30 + @copyright Warply Inc.
31 + */
32 +#import <UIKit/UIKit.h>
33 +#import <WebKit/WebKit.h>
34 +
35 +@class WLInboxItem;
36 +
37 +/*!
38 + @class WLInboxItemViewController
39 + @discussion This controller shows up modally and renders the web page of the
40 + selected offer (WLInboxItem). Also handles the click-to-action functionality
41 + specified such as pre-populated sms, QR Scanner etc.
42 + */
43 +@interface WLInboxItemViewController : UIViewController <UIWebViewDelegate, UIAlertViewDelegate>
44 +/*!
45 + @property requestedUrl
46 + @abstract An url object with link of the request offer web page.
47 + */
48 +@property (nonatomic, readonly) NSURL *requestedUrl;
49 +/*!
50 + @property session_uuid
51 + @abstract An string object with a unique session identifier.
52 + */
53 +@property (nonatomic, readonly) NSString *session_uuid;
54 +
55 +/*!
56 + @property hideNavigationArrows
57 + @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.
58 + */
59 +@property (nonatomic) BOOL hideNavigationArrows;
60 +
61 +/*!
62 + @property webView
63 + @abstract The UIWebView that displays the offer's html content. By default, the scalesPageToFit property of the webView is set to YES.
64 + */
65 +@property (nonatomic, readonly) WKWebView *webView;
66 +/*!
67 + @property fromFullPage
68 + @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.
69 + */
70 +@property (nonatomic) BOOL fromFullPage;
71 +/*!
72 + @property fromNativeAd
73 + @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.
74 + */
75 +@property (nonatomic) BOOL fromNativeAd;
76 +
77 +/*!
78 +@methodgroup Initializing a WLInboxItem View
79 +*/
80 +/*!
81 + @abstract Initialise a WLInboxItem View.
82 + @discussion Initializes and returns a newly allocated WLInboxItem View controller
83 + with the specified WLInboxItem object.
84 + @param anItem A WLInboxItem object.
85 + @return Returns WLInboxItemViewController object.
86 + @see //apple_ref/occ/cl/WLInboxItem WLInboxItem
87 + */
88 +- (id)initWithItem:(WLInboxItem*)anItem;
89 +
90 +@end
1 +/*
2 + Copyright 2010-2016 Warply Inc. All rights reserved.
3 +
4 + Redistribution and use in source and binary forms, without modification,
5 + are permitted provided that the following conditions are met:
6 +
7 + 1. Redistributions of source code must retain the above copyright notice, this
8 + list of conditions and the following disclaimer.
9 +
10 + 2. Redistributions in binaryform must reproduce the above copyright notice,
11 + this list of conditions and the following disclaimer in the documentation
12 + and/or other materials provided with the distribution.
13 +
14 + THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 + EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 + */
25 +#import "WLInboxItemViewController.h"
26 +#import "WLGlobals.h"
27 +#import "WLAnalyticsManager.h"
28 +#import "Warply.h"
29 +#import "WLInboxItem.h"
30 +#import "WLAPPActionHandler.h"
31 +
32 +///////////////////////////////////////////////////////////////////////////////
33 +@interface WLInboxItemViewController ()
34 +{
35 +@private
36 + //UI
37 + WKWebView *_webView;
38 + UIActivityIndicatorView *_activity;
39 + UIButton *_btnBack;
40 + UIButton *_btnForward;
41 +
42 + NSTimer *_timer;
43 +
44 +}
45 +
46 +@property (nonatomic, strong) WLInboxItem *item;
47 +@property (nonatomic, strong) NSTimer *timer;
48 +@property (nonatomic, assign) WLInboxItemViewController *inboxVC;
49 +
50 +- (void)updateButtons;
51 +- (void)backPressed;
52 +- (void)forwardPressed;
53 +- (void)closePressed;
54 +- (void)onTimer:(NSTimer*)sender;
55 +
56 +@end
57 +
58 +@implementation WLInboxItemViewController
59 +
60 +//Private
61 +@synthesize item = _item;
62 +@synthesize timer = _timer;
63 +
64 +#pragma mark - Initialization
65 +///////////////////////////////////////////////////////////////////////////////
66 +- (id)initWithItem:(WLInboxItem *)anItem
67 +{
68 + self = [super init];
69 + if (self) {
70 + self.item = anItem;
71 + }
72 + return self;
73 +}
74 +
75 +#pragma mark - View Lifecycle
76 +///////////////////////////////////////////////////////////////////////////////
77 +- (void)loadView
78 +{
79 + UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 480.0)];
80 + view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
81 + view.backgroundColor = [UIColor blackColor];
82 +
83 + UIView *statusView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 20.0)];
84 + statusView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
85 + statusView.backgroundColor = [UIColor whiteColor];
86 + [view addSubview:statusView];
87 +
88 + WKPreferences *preferences = [[WKPreferences alloc] init];
89 + preferences.javaScriptEnabled = YES; // Here its set
90 +
91 + // Other things you might want to disable
92 + preferences.javaScriptCanOpenWindowsAutomatically = YES;
93 +
94 + //Init WebView
95 + _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0.0, 20.0, 320.0, 480.0)];
96 + //_webView.dataDetectorTypes = UIDataDetectorTypeNone;
97 + WKWebViewConfiguration *theConfiguration = [[WKWebViewConfiguration alloc] init];
98 + theConfiguration.preferences = preferences;
99 + theConfiguration.dataDetectorTypes = UIDataDetectorTypeNone;
100 + _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0.0, 20.0, 320.0, 480.0) configuration:theConfiguration];
101 + _webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
102 + _webView.navigationDelegate = self;
103 + [view addSubview:_webView];
104 +
105 + //Init ActivityView
106 + _activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
107 + _activity.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
108 + _activity.center = _webView.center;
109 + _activity.alpha = 0.0;
110 + [view addSubview:_activity];
111 +
112 + self.view = view;
113 +}
114 +
115 +-(NSString *)session_uuid
116 +{
117 + return _item.session_uuid;
118 +}
119 +
120 +///////////////////////////////////////////////////////////////////////////////
121 +- (void)viewDidLoad
122 +{
123 + [super viewDidLoad];
124 +
125 + //Back Button
126 + _btnBack = [UIButton buttonWithType:UIButtonTypeCustom];
127 +
128 + [_btnBack setImage:[UIImage imageNamed:@"warp_white_back_button.png"] forState:UIControlStateNormal];
129 + [_btnBack sizeToFit];
130 + [_btnBack addTarget:self action:@selector(backPressed) forControlEvents:UIControlEventTouchUpInside];
131 + UIBarButtonItem *backBarButton = [[UIBarButtonItem alloc] initWithCustomView:_btnBack];
132 +
133 + //Forward Button
134 + _btnForward = [UIButton buttonWithType:UIButtonTypeCustom];
135 + [_btnForward setImage:[UIImage imageNamed:@"warp_white_forward_button.png"] forState:UIControlStateNormal];
136 + [_btnForward sizeToFit];
137 + [_btnForward addTarget:self action:@selector(forwardPressed) forControlEvents:UIControlEventTouchUpInside];
138 + UIBarButtonItem *forwardBarButton = [[UIBarButtonItem alloc] initWithCustomView:_btnForward];
139 + _btnForward.hidden = _hideNavigationArrows;
140 + _btnBack.hidden = _hideNavigationArrows;
141 +
142 + //Close Button
143 + UIButton *btnClose = [[UIButton alloc] initWithFrame:CGRectMake(0.0, 0.0, 44.0, 44.0)];
144 + btnClose.backgroundColor = [UIColor clearColor];
145 + [btnClose setImage:[UIImage imageNamed:@"warp_white_close_button.png"] forState:UIControlStateNormal];
146 + [btnClose addTarget:self action:@selector(closePressed) forControlEvents:UIControlEventTouchUpInside];
147 + UIBarButtonItem *closeBarButton = [[UIBarButtonItem alloc] initWithCustomView:btnClose];
148 +
149 +
150 + //temp close button
151 + UIButton *tmpClose = [[UIButton alloc] initWithFrame:CGRectMake(260.0, 30.0, 44.0, 44.0)];
152 +
153 + if ([UIScreen mainScreen].bounds.size.height < 568) {
154 + tmpClose.frame = CGRectMake(260.0, 30.0, 44.0, 44.0);
155 + } else if ([UIScreen mainScreen].bounds.size.height < 667) {
156 + tmpClose.frame = CGRectMake(260.0, 30.0, 44.0, 44.0);
157 + } else if ([UIScreen mainScreen].bounds.size.height < 736) {
158 + tmpClose.frame = CGRectMake(315.0, 30.0, 44.0, 44.0);
159 + } else {
160 + tmpClose.frame = CGRectMake(354.0, 30.0, 44.0, 44.0);
161 + }
162 +
163 + tmpClose.backgroundColor = [UIColor colorWithRed:0.24 green:0.29 blue:0.32 alpha:0.7];
164 + tmpClose.layer.cornerRadius = 22.0;
165 + tmpClose.clipsToBounds = YES;
166 + [tmpClose setImage:[UIImage imageNamed:@"warp_white_close_button.png"] forState:UIControlStateNormal];
167 + [tmpClose addTarget:self action:@selector(closePressed) forControlEvents:UIControlEventTouchUpInside];
168 +
169 + if (_fromFullPage || _fromNativeAd) {
170 + [self.view addSubview:tmpClose];
171 + [UIApplication sharedApplication].statusBarHidden = YES;
172 + }
173 +
174 +// [self.view addSubview:tmpClose];
175 +
176 + //Toolbar
177 + self.navigationController.toolbar.tintColor = [UIColor blackColor];
178 + if ([self.navigationController.toolbar respondsToSelector:@selector(setBarTintColor:)]) {
179 + self.navigationController.toolbar.barTintColor = [UIColor blackColor];
180 + }
181 + self.navigationController.toolbar.backgroundColor = [UIColor blackColor];;
182 + self.navigationController.toolbar.translucent = NO;
183 + UIBarButtonItem *flex = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:NULL];
184 + UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:NULL];
185 + space.width = 40.0f;
186 + NSArray *items = [NSArray arrayWithObjects: backBarButton, space, forwardBarButton, flex, closeBarButton, nil];
187 + [self setToolbarItems:items];
188 +
189 + [self.navigationController setNavigationBarHidden:YES animated:YES];
190 + [self.navigationController.tabBarController setHidesBottomBarWhenPushed:YES];
191 +
192 + [_activity startAnimating];
193 + [UIView animateWithDuration:0.5 animations:^{
194 + _activity.alpha = 1.0;
195 + }];
196 +
197 + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[_item getPageURL]]];
198 + request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
199 + [request setValue:[Warply sharedService].webId forHTTPHeaderField:@"loyalty-web-id"];
200 + [request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
201 + [request setValue:@"gzip" forHTTPHeaderField:@"User-Agent"];
202 + [_webView loadRequest:request];
203 + NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
204 +
205 + WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
206 + WKUserContentController *wkUController = [[WKUserContentController alloc] init];
207 + [wkUController addUserScript:wkUScript];
208 +
209 + WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
210 + wkWebConfig.userContentController = wkUController;
211 +
212 + _webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:wkWebConfig];
213 + self.timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(onTimer:) userInfo:nil repeats:YES];
214 + [Warply sharedService].allOffers = nil;
215 + [[Warply sharedService] getInboxWithSuccessBlock: nil failureBlock:nil];
216 +}
217 +
218 +///////////////////////////////////////////////////////////////////////////////
219 +- (void)viewDidUnload
220 +{
221 + [super viewDidUnload];
222 + [_webView setUIDelegate:nil];
223 +}
224 +
225 +///////////////////////////////////////////////////////////////////////////////
226 +- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
227 +{
228 + return (toInterfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
229 +}
230 +
231 +///////////////////////////////////////////////////////////////////////////////
232 +- (UIInterfaceOrientationMask)supportedInterfaceOrientations
233 +{
234 + return UIInterfaceOrientationMaskAllButUpsideDown;
235 +}
236 +
237 +- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
238 +{
239 + NSLog(@"createWebViewWithConfiguration %@ %@", navigationAction, windowFeatures);
240 + if (!navigationAction.targetFrame.isMainFrame) {
241 + [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
242 + [(WKWebView *)_webView loadRequest:navigationAction.request];
243 + }
244 + return nil;
245 +}
246 +#pragma mark - UIWebViewDelegater
247 +///////////////////////////////////////////////////////////////////////////////
248 +- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
249 +
250 + //NSURL *url = [navigationAction.request.URL query];
251 +
252 + if ([navigationAction.request.URL.scheme isEqualToString:@"tel"]) {
253 + UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[navigationAction.request.URL.resourceSpecifier stringByReplacingOccurrencesOfString:@"/" withString:@""] message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", @"Warply") otherButtonTitles:NSLocalizedString(@"Call", @"Warply"), nil];
254 + alert.tag = 1000;
255 + [alert show];
256 + }
257 +
258 + decisionHandler(WKNavigationActionPolicyAllow);
259 +
260 + NSString *url = navigationAction.request.URL.absoluteString;
261 +
262 + if ([navigationAction.request.URL.absoluteString containsString:@"mobile_store"]) {
263 + if ([[UIApplication sharedApplication] canOpenURL:navigationAction.request.URL]) {
264 + [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] options:@{} completionHandler:nil];
265 + [UIApplication sharedApplication].statusBarHidden = NO;
266 + [self dismissViewControllerAnimated:YES completion:nil];
267 + }
268 + }
269 + if([[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleURLTypes"]) {
270 + NSArray *urlTypes = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleURLTypes"];
271 + for(NSDictionary *urlType in urlTypes)
272 + {
273 + if(urlType[@"CFBundleURLSchemes"])
274 + {
275 + NSArray *urlSchemes = urlType[@"CFBundleURLSchemes"];
276 + for(NSString *urlScheme in urlSchemes)
277 +
278 + if ([navigationAction.request.URL.absoluteString containsString:urlScheme]) {
279 + float seconds = 2.5;
280 + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(seconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
281 + if ([[UIApplication sharedApplication] canOpenURL:navigationAction.request.URL]) {
282 + [[UIApplication sharedApplication] openURL:[NSURL URLWithString:navigationAction.request.URL.absoluteString] options:@{} completionHandler:nil];
283 + [UIApplication sharedApplication].statusBarHidden = NO;
284 + [self dismissViewControllerAnimated:YES completion:nil];
285 + }
286 + });
287 + }
288 + }
289 +
290 + }
291 + }
292 +
293 + if (navigationAction.navigationType == UIWebViewNavigationTypeLinkClicked) {
294 + if ([[UIApplication sharedApplication] canOpenURL:navigationAction.request.URL]) {
295 + [[UIApplication sharedApplication] openURL:navigationAction.request.URL options:@{} completionHandler:nil];
296 + }
297 + [UIApplication sharedApplication].statusBarHidden = NO;
298 + [self dismissViewControllerAnimated:YES completion:nil];
299 + }
300 +
301 +}
302 +
303 +- (BOOL)webView:(WKWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
304 +{
305 + _requestedUrl = request.URL;
306 +
307 + if ([request.URL.scheme isEqualToString:@"tel"]) {
308 + UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[request.URL.resourceSpecifier stringByReplacingOccurrencesOfString:@"/" withString:@""] message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", @"Warply") otherButtonTitles:NSLocalizedString(@"Call", @"Warply"), nil];
309 + alert.tag = 1000;
310 + [alert show];
311 +
312 + return NO;
313 + }
314 +
315 + [self updateButtons];
316 + WLLOG(@"WARPLY OFFER WEBVIEW REQUEST URL:%@",request.URL);
317 +
318 + if ([[Warply sharedService] handleActionUrl:_requestedUrl]) {
319 + return NO;
320 + }
321 +
322 + return YES;
323 +}
324 +
325 +///////////////////////////////////////////////////////////////////////////////
326 +//- (void)webViewDidStartLoad:(WKWebView *)webView {
327 +//
328 +//}
329 +
330 +- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
331 +}
332 +
333 +///////////////////////////////////////////////////////////////////////////////
334 +//- (void)webViewDidFinishLoad:(WKWebView *)webView
335 +//{
336 +// WLLOG(@"Finished Loading Campaign.");
337 +// [self updateButtons];
338 +// [UIView animateWithDuration:0.5
339 +// animations:^{
340 +// _activity.alpha = 0.0;
341 +// }
342 +// completion:^(BOOL finished) {
343 +// [_activity stopAnimating];
344 +// }];
345 +//}
346 +
347 +- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
348 + WLLOG(@"Finished Loading Campaign.");
349 + [self updateButtons];
350 + [UIView animateWithDuration:0.5
351 + animations:^{
352 + _activity.alpha = 0.0;
353 + }
354 + completion:^(BOOL finished) {
355 + [_activity stopAnimating];
356 + }];
357 +}
358 +///////////////////////////////////////////////////////////////////////////////
359 +//- (void)webView:(WKWebView *)webView didFailLoadWithError:(NSError *)error
360 +//{
361 +// WLLOG(@"Error while loading page = %@", [error description]);
362 +// [self updateButtons];
363 +//}
364 +
365 +- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
366 + WLLOG(@"Error while loading page = %@", [error description]);
367 + [self updateButtons];
368 +}
369 +#pragma mark - Private Methods
370 +///////////////////////////////////////////////////////////////////////////////
371 +- (void)updateButtons
372 +{
373 + _btnBack.enabled = _webView.canGoBack;
374 + _btnForward.enabled = _webView.canGoForward;
375 +}
376 +
377 +///////////////////////////////////////////////////////////////////////////////
378 +- (void)backPressed
379 +{
380 + [_webView goBack];
381 +}
382 +
383 +///////////////////////////////////////////////////////////////////////////////
384 +- (void)forwardPressed
385 +{
386 + [_webView goForward];
387 +}
388 +
389 +///////////////////////////////////////////////////////////////////////////////
390 +- (void)closePressed
391 +{
392 + [UIApplication sharedApplication].statusBarHidden = NO;
393 + [self dismissViewControllerAnimated:YES completion:nil];
394 +}
395 +
396 +///////////////////////////////////////////////////////////////////////////////
397 +- (void)onTimer:(NSTimer*)sender
398 +{
399 + [self updateButtons];
400 +}
401 +
402 +///////////////////////////////////////////////////////////////////////////////
403 +#pragma mark - Alert View Delegate
404 +// If the alert view is a call confirmation prompt send the appropriate action analytic event
405 +- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
406 +{
407 + if (alertView.tag != 1000) {
408 + return;
409 + }
410 + NSArray *callActions;
411 + switch (buttonIndex) {
412 + case 0:
413 + callActions = @[@"call_cancelled"];
414 + [WLAnalyticsManager logUrgentEventWithEventId:@"NB_CUSTOM_ACTION" pageId:@"TEL" actionMetadata:@{@"session_uuid":self.item.session_uuid, @"result": callActions}];
415 + break;
416 + default:
417 + callActions = @[@"call_clicked"];
418 + [WLAnalyticsManager logUrgentEventWithEventId:@"NB_CUSTOM_ACTION" pageId:@"TEL" actionMetadata:@{@"session_uuid":self.item.session_uuid, @"result": callActions}];
419 + [[UIApplication sharedApplication] openURL:_requestedUrl];
420 + }
421 +}
422 +
423 +#pragma mark - Memory Management
424 +///////////////////////////////////////////////////////////////////////////////
425 +- (void)dealloc
426 +{
427 + [_timer invalidate];
428 + [_webView setUIDelegate:nil];
429 +}
430 +
431 +@end
1 +/*
2 + Copyright 2010-2016 Warply Inc. All rights reserved.
3 +
4 + Redistribution and use in source and binary forms, without modification,
5 + are permitted provided that the following conditions are met:
6 +
7 + 1. Redistributions of source code must retain the above copyright notice, this
8 + list of conditions and the following disclaimer.
9 +
10 + 2. Redistributions in binaryform must reproduce the above copyright notice,
11 + this list of conditions and the following disclaimer in the documentation
12 + and/or other materials provided with the distribution.
13 +
14 + THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 + EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 + */
25 +
26 +/*!
27 + @header WLAnalyticsManager.h
28 + The Analytics Manager provides a functional interface for in-app analytics.
29 + Use the methods declared here to send in-app analytics wherever is needed within
30 + the application.
31 + @copyright Warply Inc.
32 + */
33 +
34 +#import <Foundation/Foundation.h>
35 +#import "WLBaseItem.h"
36 +
37 +/*!
38 + @class WLAnalyticsManager
39 + @discussion This manager handles the in-app analytics functionality of Warply
40 + service.
41 + */
42 +@interface WLAnalyticsManager : NSObject
43 +
44 +/*!
45 + @methodgroup Sending In-App Analytics
46 + */
47 +/*!
48 + @abstract Sends an in-app analytic.
49 + @discussion This class method sends an in-app analytic event. This event is stored
50 + into a local DB and is sent over to Warply service when a threshold of stored
51 + events is exceeded.
52 + @param event_id A string object that specifies the event that happened. Developer
53 + defined string.
54 + @param page_id A string object that specifies where the event happened. Developer
55 + defined string.
56 + @param action_metadata A dictionary object with metadata related for the event.
57 + Developer defined dictionary.
58 + @seealso //apple_ref/occ/clm/WLAnalyticsManager/sendAnalyticsEventWithEvent_id:page_id:action_metadata: sendAnalyticsEventWithEvent_id:page_id:action_metadata:
59 + */
60 ++ (void)logEventWithEventId:(NSString *)event_id pageId:(NSString *)page_id actionMetadata:(NSDictionary *)action_metadata;
61 +/*!
62 + @abstract Sends an Urgent in-app analytic.
63 + @discussion This class method sends an urgent in-app analytic event. This event
64 + is sent to Warply service immediately. It is advised to use this type of event only
65 + in places of the application where almost real-time analytic reporting is required.
66 + @param event_id A string object that specifies the event that happened. Developer
67 + defined string.
68 + @param page_id A string object that specifies where the event happened. Developer
69 + defined string.
70 + @param action_metadata A dictionary object with metadata related for the event.
71 + Developer defined dictionary.
72 + @seealso //apple_ref/occ/clm/WLAnalyticsManager/sendPriorityAnalyticsEventWithEvent_id:page_id:action_metadata: sendPriorityAnalyticsEventWithEvent_id:page_id:action_metadata:
73 + */
74 ++ (void)logUrgentEventWithEventId:(NSString *)eventId pageId:(NSString *)pageId actionMetadata:(NSDictionary *)action_metadata;
75 +/*!
76 + @abstract Sends an in-app analytic event indicating that the user interacted with the push.
77 + @param item The WLBaseItem representation of the push payload. You can create it like this: WLBaseItem *item = [WLBaseItem alloc] initWithAttributes:payload];
78 + terminates.
79 + */
80 ++ (void)logUserEngagedPush:(WLBaseItem *)item;
81 +
82 ++ (void)logUserReceivedPush:(WLBaseItem *)item;
83 +
84 +//TODO: Add documentation
85 ++ (void)logAppDidFinishLauchingEvent;
86 ++ (void)logAppWillEnterForegroundEvent;
87 ++ (void)logAppWillTerminateEvent;
88 ++ (void)logAppDidEnterBackgroundEvent;
89 +
90 +
91 +@end
1 +/*
2 + Copyright 2010-2016 Warply Inc. All rights reserved.
3 +
4 + Redistribution and use in source and binary forms, without modification,
5 + are permitted provided that the following conditions are met:
6 +
7 + 1. Redistributions of source code must retain the above copyright notice, this
8 + list of conditions and the following disclaimer.
9 +
10 + 2. Redistributions in binaryform must reproduce the above copyright notice,
11 + this list of conditions and the following disclaimer in the documentation
12 + and/or other materials provided with the distribution.
13 +
14 + THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 + EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 + */
25 +
26 +#import "WLAnalyticsManager.h"
27 +#import "Warply.h"
28 +
29 +@implementation WLAnalyticsManager
30 +
31 +#pragma mark - Static Public Methods
32 +///////////////////////////////////////////////////////////////////////////////
33 ++ (void)logEventWithEventId:(NSString *)eventId
34 + pageId:(NSString *)pageId
35 + actionMetadata:(NSDictionary *)actionMetadata
36 +{
37 + if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_CUSTOM_ANALYTICS_ENABLED))
38 + return;
39 +
40 + [self internalLogEventWithEventId:eventId
41 + pageId:pageId
42 + actionMetadata:actionMetadata];
43 +}
44 +
45 +///////////////////////////////////////////////////////////////////////////////
46 ++ (void)logUrgentEventWithEventId:(NSString *)eventId
47 + pageId:(NSString *)pageId
48 + actionMetadata:(NSDictionary *)actionMetadata
49 +{
50 + if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_CUSTOM_ANALYTICS_ENABLED))
51 + return;
52 +
53 + [self internalLogUrgentEventWithEventId:eventId
54 + pageId:pageId
55 + actionMetadata:actionMetadata];
56 +}
57 +
58 +///////////////////////////////////////////////////////////////////////////////
59 ++ (void)logAppDidFinishLauchingEvent
60 +{
61 + if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_LIFECYCLE_ANALYTICS_ENABLED))
62 + return;
63 +
64 + [WLAnalyticsManager internalLogEventWithEventId:@"NB_DidFinishLaunching"
65 + pageId:@"NB_APP"
66 + actionMetadata:nil];
67 +}
68 +
69 +///////////////////////////////////////////////////////////////////////////////
70 ++ (void)logAppWillEnterForegroundEvent
71 +{
72 + if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_LIFECYCLE_ANALYTICS_ENABLED))
73 + return;
74 + if([[NSUserDefaults standardUserDefaults] boolForKey:WL_LIFECYCLE_ANALYTICS_ENABLED]) {
75 + [WLAnalyticsManager internalLogEventWithEventId:@"session"
76 + pageId:@"NB_APP"
77 + actionMetadata:nil];
78 + }
79 +}
80 +
81 +///////////////////////////////////////////////////////////////////////////////
82 ++ (void)logAppWillTerminateEvent
83 +{
84 + if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_LIFECYCLE_ANALYTICS_ENABLED))
85 + return;
86 +
87 + [WLAnalyticsManager internalLogEventWithEventId:@"NB_WillTerminate"
88 + pageId:@"NB_APP"
89 + actionMetadata:nil];
90 +}
91 +
92 +///////////////////////////////////////////////////////////////////////////////
93 ++ (void)logAppDidEnterBackgroundEvent
94 +{
95 + if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_LIFECYCLE_ANALYTICS_ENABLED))
96 + return;
97 +
98 + [WLAnalyticsManager internalLogEventWithEventId:@"session"
99 + pageId:@"NB_APP"
100 + actionMetadata:nil];
101 +}
102 +
103 +#pragma mark - Static Private Methods
104 +///////////////////////////////////////////////////////////////////////////////
105 ++ (void)internalLogEventWithEventId:(NSString *)eventId
106 + pageId:(NSString *)pageId
107 + actionMetadata:(NSDictionary *)actionMetadata
108 +{
109 + NSNumber *time_submitted = [NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]];
110 + NSDictionary *inapp_event = [NSDictionary dictionaryWithObjectsAndKeys:eventId, @"event_id", pageId, @"page_id", time_submitted, @"time_submitted", actionMetadata, @"action_metadata", nil];
111 + NSDictionary *eventContext = [NSDictionary dictionaryWithObject:inapp_event forKey:@"inapp_analytics"];
112 + WLEventSimple *event = [[WLEventSimple alloc] initWithType:@"inapp_analytics" andContext:eventContext];
113 + [[Warply sharedService] addEvent:event priority:NO];
114 +}
115 +
116 +///////////////////////////////////////////////////////////////////////////////
117 ++ (void)internalLogUrgentEventWithEventId:(NSString *)eventId
118 + pageId:(NSString *)pageId
119 + actionMetadata:(NSDictionary *)actionMetadata
120 +{
121 + NSNumber *time_submitted = [NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]];
122 + NSDictionary *inapp_event = [NSDictionary dictionaryWithObjectsAndKeys:eventId, @"event_id", pageId, @"page_id", time_submitted, @"time_submitted", actionMetadata, @"action_metadata", nil];
123 + NSDictionary *eventContext = [NSDictionary dictionaryWithObject:inapp_event forKey:@"inapp_analytics"];
124 + WLEventSimple *event = [[WLEventSimple alloc] initWithType:@"inapp_analytics" andContext:eventContext];
125 + [[Warply sharedService] addEvent:event priority:YES];
126 +}
127 +
128 +#pragma mark - Push Analytics
129 +///////////////////////////////////////////////////////////////////////////////
130 ++ (void)logUserEngagedPush:(WLBaseItem *)item
131 +{
132 + [WLAnalyticsManager internalLogUrgentEventWithEventId:@"NB_PushAck"
133 + pageId:@"NB_APP"
134 + actionMetadata:[NSDictionary dictionaryWithObjectsAndKeys:item.session_uuid, @"session_uuid", nil]];
135 +}
136 +
137 +///////////////////////////////////////////////////////////////////////////////
138 ++ (void)logUserReceivedPush:(WLBaseItem *)item
139 +{
140 + [WLAnalyticsManager internalLogUrgentEventWithEventId:@"NB_PushReceived"
141 + pageId:@"NB_APP"
142 + actionMetadata:[NSDictionary dictionaryWithObjectsAndKeys:item.session_uuid, @"session_uuid", nil]];
143 +}
144 +
145 +@end
1 +/*
2 + Copyright 2010-2016 Warply Inc. All rights reserved.
3 +
4 + Redistribution and use in source and binary forms, without modification,
5 + are permitted provided that the following conditions are met:
6 +
7 + 1. Redistributions of source code must retain the above copyright notice, this
8 + list of conditions and the following disclaimer.
9 +
10 + 2. Redistributions in binaryform must reproduce the above copyright notice,
11 + this list of conditions and the following disclaimer in the documentation
12 + and/or other materials provided with the distribution.
13 +
14 + THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 + EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 + */
25 +
26 +/*!
27 + @header WLBeaconManager.h
28 +The Beacon Manager provides functionality for iBeacons detection and serving advertisements related to the beacons that are scanned from the device.
29 + @copyright Warply Inc.
30 + */
31 +
32 +#import <UIKit/UIKit.h>
33 +#import <CoreLocation/CoreLocation.h>
34 +
35 +@class WLInboxItem;
36 +@class WLBaseItem;
37 +
38 +
39 +
40 +/*!
41 + @class WLBeaconManager
42 + @discussion This manager handles beacon served campaigns and detecting iBeacon devices in range.
43 + service.
44 + */
45 +@interface WLBeaconManager : NSObject
46 +
47 +/*!
48 + @property pendingItem
49 + @abstract The remote notification as a WLBaseItem currently stored for later use.
50 + */
51 +@property (nonatomic, strong) WLBaseItem *pendingItem;
52 +
53 +@property (strong, nonatomic) CLLocationManager *locationManager;
54 +
55 +/*!
56 + @methodgroup Getting Shared Instance
57 + */
58 +/*!
59 + @abstract Returns a shared instance of WLBeaconManager.
60 + */
61 ++ (WLBeaconManager *)sharedInstance;
62 +/*!
63 + @methodgroup Launching beacon manager and beacon monitoring.
64 + */
65 +/*!
66 + @abstract Launching the Warply Beacon Manager.
67 + @discussion This method initialises the shared instance of WLBeaconManager and passes an array of the beacon identifiers that the manager will search for.
68 + @param devices An array of beacon UUID's and identifiers for the manager to monitor.
69 + */
70 +- (void) startMonitorWithBeaconsArray:(NSArray*)devices;
71 +/*!
72 + @abstract Shows the campaign that was received from a beacon device.
73 + @discussion This class method presents the campaign that is bounded with an iBeacon device after a successful retrieval of the data of the campaign.
74 + @param item The WLInboxItem that contains all the necessary data of the campaign to be presented.
75 + */
76 ++ (void)showItem:(WLInboxItem*)item;
77 +
78 +@end
1 +//
2 +// WLBeaconManager.m
3 +// DemoApp
4 +//
5 +// Created by Warply on 09.06.15.
6 +// Copyright (c) 2015 YC. All rights reserved.
7 +//
8 +
9 +#import "WLBeaconManager.h"
10 +#import "Warply.h"
11 +#import <CoreLocation/CoreLocation.h>
12 +#include <mach/mach.h>
13 +#include <mach/mach_time.h>
14 +#import <math.h>
15 +#import "WLInboxItemViewController.h"
16 +#import "UIViewController+WLAdditions.h"
17 +#import "WLBaseItem.h"
18 +
19 +
20 +
21 +
22 +
23 +
24 +@interface WLBeaconManager () <CLLocationManagerDelegate>
25 +//@property (nonatomic, strong) CLLocationManager* locationManager;
26 +
27 +@property(nonatomic, strong) NSArray *beaconRegions;
28 +@property (nonatomic, strong) NSMutableSet* insideBeaconRegions;
29 +@property (strong, nonatomic) NSMutableArray *alreadyCheckedBeacon;
30 +@end
31 +
32 +
33 +@implementation WLBeaconManager{
34 + NSInteger currentTime;
35 +}
36 +
37 ++ (WLBeaconManager *)sharedInstance{
38 + static dispatch_once_t pred;
39 + static WLBeaconManager *shared = nil;
40 + dispatch_once(&pred, ^{
41 + shared = [[WLBeaconManager alloc] init];
42 + });
43 + return shared;
44 +}
45 +
46 +- (instancetype)init{
47 +
48 + if (self = [super init]) {
49 + self.locationManager = [[CLLocationManager alloc] init];
50 + self.locationManager.delegate = self;
51 + self.alreadyCheckedBeacon = [NSMutableArray array];
52 +
53 + NSString *identifier = @"Warply";
54 + NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:@"9439f6fb-8895-40e9-9849-57454fd9b228"];
55 +
56 + // NSString *identifier = @"Place 1";
57 + // NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:@"B9407F30-F5F8-466E-AFF9-25556B57FE6D"];
58 +
59 + CLBeaconRegion *beacon = [[CLBeaconRegion alloc] initWithProximityUUID:uuid identifier:identifier];
60 + beacon.notifyOnEntry = YES;
61 + beacon.notifyOnExit = YES;
62 + beacon.notifyEntryStateOnDisplay = YES;
63 +
64 + if([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
65 + [self.locationManager requestAlwaysAuthorization];
66 + }
67 +
68 + currentTime = (NSInteger)getTickCount();
69 + self.locationManager.pausesLocationUpdatesAutomatically = NO;
70 + [self.locationManager startMonitoringSignificantLocationChanges];
71 + [self.locationManager startMonitoringForRegion:beacon];
72 + }
73 +
74 + return self;
75 +}
76 +
77 +- (void) startMonitorWithBeaconsArray:(NSArray*)devices{
78 +
79 + NSInteger timeInterval = [[NSUserDefaults standardUserDefaults] integerForKey:WL_BEACON_TIME_INTERVAL_TO_RESEND];
80 + NSLog(@"Time interval %ld", (long)timeInterval);
81 +
82 + NSMutableArray *tempArray = [NSMutableArray array];
83 +
84 + for (NSDictionary *item in devices) {
85 + NSUUID *beaconUUID = [[NSUUID alloc] initWithUUIDString:item[@"UUID"]];
86 + NSString *beaconIdentifier = item[@"beaconIdentifier"];
87 + CLBeaconRegion *region = [[CLBeaconRegion alloc] initWithProximityUUID:beaconUUID identifier:beaconIdentifier];
88 + [self.locationManager startMonitoringForRegion:region];
89 + [self.locationManager startRangingBeaconsInRegion:region];
90 +
91 + [self.locationManager startUpdatingLocation];
92 + }
93 +
94 + _beaconRegions = tempArray;
95 +}
96 +
97 +- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
98 +
99 + if (status == kCLAuthorizationStatusAuthorizedAlways) {
100 + [self.locationManager startUpdatingLocation];
101 + } else if (status == kCLAuthorizationStatusAuthorizedWhenInUse) {
102 + [self.locationManager startUpdatingLocation];
103 + }else if (status == kCLAuthorizationStatusRestricted){
104 + NSLog(@"Need Location Service Permission To Access Beacon");
105 + } else if(status == kCLAuthorizationStatusDenied){
106 + NSLog(@"Need Location Service Permission To Access Beacon");
107 + } else {
108 + NSLog(@"Need Location Service Permission To Access Beacon");
109 + }
110 +}
111 +
112 +- (void)locationManager:(CLLocationManager *)manager didDetermineState:(CLRegionState)state forRegion:(CLBeaconRegion *)region
113 +{
114 + if (state == CLRegionStateInside) {
115 + [self.locationManager startRangingBeaconsInRegion:region];
116 + NSLog(@"inside region %@", region.proximityUUID.UUIDString);
117 + } else if (state == CLRegionStateOutside) {
118 + [self.locationManager stopRangingBeaconsInRegion:region];
119 + } else {
120 + //unknown?
121 + }
122 +}
123 +
124 +- (void)locationManager:(CLLocationManager *)manager didStartMonitoringForRegion:(CLRegion *)region {
125 + NSLog(@"start monitoring");
126 + [self.locationManager requestStateForRegion:region];
127 +}
128 +
129 +- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLBeaconRegion *)region
130 +{
131 + NSLog(@"Enter region %@", region.proximityUUID.UUIDString);
132 + // [self showMessage:@"Hello"];
133 +}
134 +
135 +- (void)locationManager:(CLLocationManager *)manager didExitRegion:(CLBeaconRegion *)region
136 +{
137 + NSLog(@"Exit region %@", region.proximityUUID.UUIDString);
138 + // [self showMessage:@"Bye"];
139 +}
140 +
141 +
142 +
143 +-(void)locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray *)beacons inRegion:(CLBeaconRegion *)region {
144 +
145 + NSLog(@"beacons count %@", beacons);
146 + for (CLBeacon *foundBeacon in beacons) {
147 +
148 + if (_alreadyCheckedBeacon.count == 0) {
149 + // NSLog(@"found beacon's uuid %@\t%@\t%@", foundBeacon.proximityUUID.UUIDString, foundBeacon.major, foundBeacon.minor);
150 + [_alreadyCheckedBeacon addObject:foundBeacon];
151 + [self getDateFromBeacon:foundBeacon];
152 + } else {
153 +
154 + BOOL beaconExists = NO;
155 + for (CLBeacon *savedBeacon in _alreadyCheckedBeacon) {
156 +
157 + NSInteger timeInterval;
158 + if ([[NSUserDefaults standardUserDefaults] integerForKey:WL_BEACON_TIME_INTERVAL_TO_RESEND] > 0) {
159 + timeInterval = [[NSUserDefaults standardUserDefaults] integerForKey:WL_BEACON_TIME_INTERVAL_TO_RESEND];
160 + } else {
161 + timeInterval = 3600000;
162 + }
163 +
164 +
165 + if ([savedBeacon.proximityUUID.UUIDString.lowercaseString isEqualToString:foundBeacon.proximityUUID.UUIDString.lowercaseString] && savedBeacon.major.intValue == foundBeacon.major.intValue && savedBeacon.minor.intValue == foundBeacon.minor.intValue) {
166 +
167 + beaconExists = YES;
168 +
169 + if (getTickCount() - currentTime >= timeInterval) {
170 + [self getDateFromBeacon:foundBeacon];
171 + }
172 + }
173 + }
174 +
175 + if (!beaconExists) {
176 +
177 + // NSLog(@"found beacon's uuid %@\t%d\t%d", foundBeacon.proximityUUID.UUIDString.lowercaseString, foundBeacon.major.intValue, foundBeacon.minor.intValue);
178 + // NSLog(@"saved beacon's uuid %@\t%d\t%d", savedBeacon.proximityUUID.UUIDString.lowercaseString, savedBeacon.major.intValue, savedBeacon.minor.intValue);
179 +
180 + // NSLog(@"found beacons count %lu", (unsigned long)_alreadyCheckedBeacon.count);
181 +
182 + [_alreadyCheckedBeacon addObject:foundBeacon];
183 + [self getDateFromBeacon:foundBeacon];
184 + }
185 + }
186 +
187 + }
188 +}
189 +
190 +
191 +-(void)getDateFromBeacon:(CLBeacon *)beacon {
192 +
193 +
194 + NSString *uuid = beacon.proximityUUID.UUIDString;
195 + NSString *major = [NSString stringWithFormat:@"%@", beacon.major];
196 + NSString *minor = [NSString stringWithFormat:@"%@", beacon.minor];
197 +
198 + // NSLog(@"beacon's uuid %@\t%@\t%@", beacon.proximityUUID.UUIDString, beacon.major, beacon.minor);
199 + // NSLog(@"saved beacons in array %@", _alreadyCheckedBeacon);
200 + // NSLog(@"time difference %llu", getTickCount() - currentTime);
201 +
202 + currentTime = (NSInteger)getTickCount();
203 +
204 + NSDictionary *postDictionary = @{@"beacon":@{@"data":@[@{@"uuid":uuid.lowercaseString, @"major":major, @"minor": minor, @"distance":@(beacon.accuracy)}], @"action": @"beacon"}};
205 + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDictionary options:0 error:NULL];
206 +
207 +
208 + [[Warply sharedService] sendContext:jsonData successBlock:^(NSDictionary *contextResponse) {
209 +
210 + // NSLog(@"beacon response %@", contextResponse);
211 + if ([[contextResponse valueForKey:@"MAPP_BEACON-status"] integerValue] == 1 && [contextResponse[@"MAPP_BEACON"] isKindOfClass:[NSArray class]]) {
212 + [self sendLocalNotificationWithMessage:contextResponse];
213 + }
214 +
215 +
216 + } failureBlock:^(NSError *error) {
217 + NSLog(@"Beacon error %@", error);
218 + }];
219 +}
220 +
221 +
222 +-(void)sendLocalNotificationWithMessage:(NSDictionary*)message {
223 +
224 + if (message != nil) {
225 +
226 + self.pendingItem = [[WLBaseItem alloc] initWithAttributes:message[@"MAPP_BEACON"][0]];
227 +
228 + UIApplicationState state = [[UIApplication sharedApplication] applicationState];
229 + if (state == UIApplicationStateActive)
230 + {
231 + UIAlertView *alert = [[UIAlertView alloc] init];
232 + [alert setTitle:message[@"MAPP_BEACON"][0][@"message"]];
233 + [alert addButtonWithTitle:NSLocalizedString(@"Close", @"Warply")];
234 + [alert addButtonWithTitle:NSLocalizedString(@"View", @"Warply")];
235 + [alert setDelegate:self];
236 + [alert show];
237 +
238 + }else{
239 + UILocalNotification *notification = [[UILocalNotification alloc] init];
240 + notification.alertBody = message[@"MAPP_BEACON"][0][@"message"];
241 + notification.userInfo = @{@"test": @"value"};
242 + notification.soundName = UILocalNotificationDefaultSoundName;
243 + [[UIApplication sharedApplication] scheduleLocalNotification:notification];
244 + }
245 + }
246 +}
247 +
248 +uint64_t getTickCount(void)
249 +{
250 + static mach_timebase_info_data_t sTimebaseInfo;
251 + uint64_t machTime = mach_absolute_time();
252 + NSLog(@"mach time: %llu", machTime);
253 + // Convert to nanoseconds - if this is the first time we've run, get the timebase.
254 + if (sTimebaseInfo.denom == 0 )
255 + {
256 + (void) mach_timebase_info(&sTimebaseInfo);
257 + }
258 +
259 + // Convert the mach time to milliseconds
260 + uint64_t millis = ((machTime / 1000000) * sTimebaseInfo.numer) / sTimebaseInfo.denom;
261 + return millis;
262 +}
263 +
264 +- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
265 +{
266 + if (buttonIndex == 1) {
267 + [WLAnalyticsManager logUserEngagedPush:self.pendingItem];
268 + if (self.pendingItem == nil)
269 + return;
270 +
271 + WLInboxItem *inboxItem = [[WLInboxItem alloc] initWithItem:self.pendingItem];
272 + [WLBeaconManager showItem:inboxItem];
273 + self.pendingItem = nil;
274 + }
275 +}
276 +
277 ++ (void)showItem:(WLInboxItem*)item
278 +{
279 + WLInboxItemViewController *itemViewController = [[WLInboxItemViewController alloc] initWithItem:item];
280 + // itemViewController.fromFullPage = YES;
281 + itemViewController.view.userInteractionEnabled = YES;
282 +
283 + UINavigationController *newModalController = [[UINavigationController alloc] initWithRootViewController:itemViewController];
284 +
285 + newModalController.navigationBarHidden = YES;
286 + newModalController.toolbarHidden = NO;
287 +
288 + //UIViewController *existingModalController = [UIApplication sharedApplication].delegate.window.rootViewController.navigationController.viewControllers.firstObject;
289 + UIViewController *existingModalController = [[UIApplication sharedApplication].delegate.window.rootViewController topModalViewController];
290 +
291 + NSLog(@"View Controller %@", [[UIApplication sharedApplication].delegate.window.rootViewController topModalViewController]);
292 +
293 + if (existingModalController == nil) {
294 + 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];
295 + [alert show];
296 +
297 + return;
298 + }
299 +
300 + [existingModalController presentViewController:newModalController animated:YES completion:nil];
301 +}
302 +
303 +
304 +
305 +- (void) showMessage: (NSString*) message {
306 +
307 + NSLog(@"Show notification for region");
308 +
309 +
310 + UILocalNotification *notification = [[UILocalNotification alloc] init];
311 + notification.alertBody = message;
312 + notification.soundName = UILocalNotificationDefaultSoundName;
313 + notification.applicationIconBadgeNumber = 1;
314 + [[UIApplication sharedApplication] scheduleLocalNotification:notification];
315 +
316 + //
317 + // UIApplicationState state = [[UIApplication sharedApplication] applicationState];
318 + // if (state == UIApplicationStateBackground)
319 + // {
320 + // UILocalNotification *notification = [[UILocalNotification alloc] init];
321 + // notification.alertBody = message;
322 + // notification.soundName = UILocalNotificationDefaultSoundName;
323 + // [[UIApplication sharedApplication] scheduleLocalNotification:notification];
324 + //
325 + //
326 + // }else{
327 + // UIAlertView *alert = [[UIAlertView alloc] init];
328 + //// [alert setTitle:message[@"MAPP_BEACON"][0][@"message"]];
329 + //// [alert addButtonWithTitle:NSLocalizedString(@"Close", @"Warply")];
330 + //// [alert addButtonWithTitle:NSLocalizedString(@"View", @"Warply")];
331 + //// [alert setDelegate:self];
332 + // alert.title = message;
333 + // [alert addButtonWithTitle:@"Ok"];
334 + // [alert show];
335 + // }
336 +
337 +}
338 +
339 +@end
340 +
341 +
342 +
343 +
344 +
345 +
346 +
347 +//@interface WLBeaconManager () <CLLocationManagerDelegate>
348 +//
349 +//@property(nonatomic, strong) NSArray *beaconRegions;
350 +//@property (strong, nonatomic) CLLocationManager *locationManager;
351 +//@property (strong, nonatomic) NSMutableArray *alreadyCheckedBeacon;
352 +//
353 +//@end
354 +//
355 +//
356 +//
357 +//
358 +//
359 +//@implementation WLBeaconManager{
360 +// NSInteger currentTime;
361 +//}
362 +//
363 +//+ (WLBeaconManager *)sharedInstance{
364 +// static dispatch_once_t pred;
365 +// static WLBeaconManager *shared = nil;
366 +// dispatch_once(&pred, ^{
367 +// shared = [[WLBeaconManager alloc] init];
368 +// });
369 +// return shared;
370 +//}
371 +//
372 +//- (instancetype)init{
373 +// if (self = [super init]) {
374 +// self.locationManager = [[CLLocationManager alloc] init];
375 +// self.alreadyCheckedBeacon = [NSMutableArray array];
376 +// if([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
377 +// [self.locationManager requestAlwaysAuthorization];
378 +// [self.locationManager startMonitoringSignificantLocationChanges];
379 +// self.locationManager.allowsBackgroundLocationUpdates = YES;
380 +// currentTime = (NSInteger)getTickCount();
381 +// }
382 +//
383 +// self.locationManager.delegate = self;
384 +// }
385 +//
386 +// return self;
387 +//}
388 +//
389 +//- (void) startMonitorWithBeaconsArray:(NSArray*)devices{
390 +//
391 +// NSInteger timeInterval = [[NSUserDefaults standardUserDefaults] integerForKey:WL_BEACON_TIME_INTERVAL_TO_RESEND];
392 +// NSLog(@"Time interval %ld", (long)timeInterval);
393 +//
394 +// NSMutableArray *tempArray = [NSMutableArray array];
395 +//
396 +// for (NSDictionary *item in devices) {
397 +// NSUUID *beaconUUID = [[NSUUID alloc] initWithUUIDString:item[@"UUID"]];
398 +// NSString *beaconIdentifier = item[@"beaconIdentifier"];
399 +// CLBeaconRegion *region = [[CLBeaconRegion alloc] initWithProximityUUID:beaconUUID identifier:beaconIdentifier];
400 +// [self.locationManager startMonitoringForRegion:region];
401 +// [self.locationManager startRangingBeaconsInRegion:region];
402 +//
403 +// [self.locationManager startUpdatingLocation];
404 +// }
405 +//
406 +// _beaconRegions = tempArray;
407 +//}
408 +//
409 +//
410 +//
411 +////- (void)locationManager:(CLLocationManager*)manager didEnterRegion:(CLRegion*)region
412 +////{
413 +//// [self.locationManager startRangingBeaconsInRegion:(CLBeaconRegion *)region];
414 +////// UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"In region" message:nil delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
415 +////// [alert show];
416 +////}
417 +////
418 +////
419 +////
420 +////-(void)locationManager:(CLLocationManager*)manager didExitRegion:(CLRegion*)region
421 +////{
422 +//// [self.locationManager stopRangingBeaconsInRegion:(CLBeaconRegion *)region];
423 +////// UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Out region" message:nil delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
424 +////// [alert show];
425 +////}
426 +//
427 +//
428 +//
429 +//-(void)locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray *)beacons inRegion:(CLBeaconRegion *)region {
430 +//
431 +// NSLog(@"beacons count %@", beacons);
432 +// for (CLBeacon *foundBeacon in beacons) {
433 +//
434 +// if (_alreadyCheckedBeacon.count == 0) {
435 +// [_alreadyCheckedBeacon addObject:foundBeacon];
436 +// [self getDateFromBeacon:foundBeacon];
437 +// } else {
438 +// for (CLBeacon *savedBeacon in _alreadyCheckedBeacon) {
439 +// if (![savedBeacon.proximityUUID.UUIDString isEqualToString:foundBeacon.proximityUUID.UUIDString] &&
440 +// savedBeacon.major != foundBeacon.major && savedBeacon.minor != foundBeacon.minor && (getTickCount() - currentTime >= 6000)) {
441 +//
442 +// [_alreadyCheckedBeacon addObject:foundBeacon];
443 +// NSLog(@"found beacons count %lu", (unsigned long)_alreadyCheckedBeacon.count);
444 +// [self getDateFromBeacon:foundBeacon];
445 +// }
446 +// }
447 +// }
448 +//
449 +// }
450 +//}
451 +//
452 +//
453 +//
454 +//-(void)getDateFromBeacon:(CLBeacon *)beacon {
455 +//
456 +//
457 +// NSString *uuid = beacon.proximityUUID.UUIDString;
458 +// NSString *major = [NSString stringWithFormat:@"%@", beacon.major];
459 +// NSString *minor = [NSString stringWithFormat:@"%@", beacon.minor];
460 +//
461 +// NSLog(@"beacon's uuid %@", beacon.proximityUUID.UUIDString);
462 +// NSLog(@"saved beacons in array %@", _alreadyCheckedBeacon);
463 +// NSLog(@"time difference %llu", getTickCount() - currentTime);
464 +//
465 +// currentTime = (NSInteger)getTickCount();
466 +//
467 +// NSDictionary *postDictionary = @{@"beacon":@{@"data":@[@{@"uuid":uuid, @"major":major, @"minor": minor, @"distance":@(beacon.accuracy)}], @"action": @"beacon"}};
468 +// NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDictionary options:0 error:NULL];
469 +//
470 +//
471 +// [[Warply sharedService] sendContext:jsonData successBlock:^(NSDictionary *contextResponse) {
472 +//
473 +// NSLog(@"beacon response %@", contextResponse);
474 +// if ([[contextResponse valueForKey:@"MAPP_BEACON-status"] integerValue] == 1 && [contextResponse[@"MAPP_BEACON"] isKindOfClass:[NSArray class]]) {
475 +// [self sendLocalNotificationWithMessage:contextResponse];
476 +// }
477 +//
478 +//
479 +// } failureBlock:^(NSError *error) {
480 +// NSLog(@"Beacon error %@", error);
481 +// }];
482 +//}
483 +//
484 +//
485 +//-(void)sendLocalNotificationWithMessage:(NSDictionary*)message {
486 +//
487 +// if (message != nil) {
488 +//
489 +// self.pendingItem = [[WLBaseItem alloc] initWithAttributes:message[@"MAPP_BEACON"][0]];
490 +//
491 +// UIApplicationState state = [[UIApplication sharedApplication] applicationState];
492 +// if (state == UIApplicationStateActive)
493 +// {
494 +// UIAlertView *alert = [[UIAlertView alloc] init];
495 +// [alert setTitle:message[@"MAPP_BEACON"][0][@"message"]];
496 +// [alert addButtonWithTitle:NSLocalizedString(@"Close", @"Warply")];
497 +// [alert addButtonWithTitle:NSLocalizedString(@"View", @"Warply")];
498 +// [alert setDelegate:self];
499 +// [alert show];
500 +//
501 +// }else{
502 +// UILocalNotification *notification = [[UILocalNotification alloc] init];
503 +// notification.alertBody = message[@"MAPP_BEACON"][0][@"message"];
504 +// notification.userInfo = @{@"test": @"value"};
505 +// [[UIApplication sharedApplication] scheduleLocalNotification:notification];
506 +// }
507 +// }
508 +//}
509 +//
510 +//uint64_t getTickCount(void)
511 +//{
512 +// static mach_timebase_info_data_t sTimebaseInfo;
513 +// uint64_t machTime = mach_absolute_time();
514 +// NSLog(@"mach time: %llu", machTime);
515 +// // Convert to nanoseconds - if this is the first time we've run, get the timebase.
516 +// if (sTimebaseInfo.denom == 0 )
517 +// {
518 +// (void) mach_timebase_info(&sTimebaseInfo);
519 +// }
520 +//
521 +// // Convert the mach time to milliseconds
522 +// uint64_t millis = ((machTime / 1000000) * sTimebaseInfo.numer) / sTimebaseInfo.denom;
523 +// return millis;
524 +//}
525 +//
526 +//- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
527 +//{
528 +// if (buttonIndex == 1) {
529 +// [WLAnalyticsManager logUserEngagedPush:self.pendingItem];
530 +// if (self.pendingItem == nil)
531 +// return;
532 +//
533 +// WLInboxItem *inboxItem = [[WLInboxItem alloc] initWithItem:self.pendingItem];
534 +// [WLBeaconManager showItem:inboxItem];
535 +// self.pendingItem = nil;
536 +// }
537 +//}
538 +//
539 +//+ (void)showItem:(WLInboxItem*)item
540 +//{
541 +// WLInboxItemViewController *itemViewController = [[WLInboxItemViewController alloc] initWithItem:item];
542 +//
543 +// UINavigationController *newModalController = [[UINavigationController alloc] initWithRootViewController:itemViewController];
544 +//
545 +// newModalController.navigationBarHidden = YES;
546 +// newModalController.toolbarHidden = NO;
547 +//
548 +// UIViewController *existingModalController = [[UIApplication sharedApplication].delegate.window.rootViewController topModalViewController];
549 +//
550 +// if (existingModalController == nil) {
551 +// 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];
552 +// [alert show];
553 +//
554 +// return;
555 +// }
556 +//
557 +// [existingModalController presentViewController:newModalController animated:YES completion:nil];
558 +//}
559 +//
560 +//@end
1 +/*
2 + Copyright 2010-2016 Warply Inc. All rights reserved.
3 +
4 + Redistribution and use in source and binary forms, without modification,
5 + are permitted provided that the following conditions are met:
6 +
7 + 1. Redistributions of source code must retain the above copyright notice, this
8 + list of conditions and the following disclaimer.
9 +
10 + 2. Redistributions in binaryform must reproduce the above copyright notice,
11 + this list of conditions and the following disclaimer in the documentation
12 + and/or other materials provided with the distribution.
13 +
14 + THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 + EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 + */
25 +
26 +/*!
27 + @header WLLocationManager.h
28 + The Location Manager provides a functional interface to the Core Location.
29 + Use the methods declared here to start and stop report location manually or
30 + automatically during app lifecycle.
31 + @copyright Warply Inc.
32 + */
33 +
34 +#import <Foundation/Foundation.h>
35 +#import <CoreLocation/CoreLocation.h>
36 +
37 +@protocol WLLocationManagerDelegate;
38 +
39 +/*!
40 + @typedef WLLocationForegroundMode
41 + @abstract The modes of location monitoring. These correspond to the modes of the CLLocationManager.
42 + @field WLLocationForegroundModeOff The application does not send the server it's location.
43 + @field WLLocationForegroundModeSignificant The application sends the device's location only on significant location changes.
44 + @field WLLocationForegroundModeStandard The application sends the device's location at times/distances defined by the corresponding parameters.
45 + */
46 +typedef enum WLLocationForegroundMode : unsigned int{
47 + WLLocationModeOff = 0,
48 + WLLocationModeSignificant,
49 + WLLocationModeStandard
50 +}WLLocationForegroundMode;
51 +
52 +/*!
53 + @class WLLocationManager
54 + @discussion This manager handles the geo-location functionality of Warply service.
55 + */
56 +@interface WLLocationManager : NSObject <CLLocationManagerDelegate>
57 +
58 +/*!
59 + @property locationManager
60 + @abstract A CLLocationManager.
61 + */
62 +@property (nonatomic, strong) CLLocationManager *locationManager;
63 +
64 +/*!
65 + @property locationManagerDelegate
66 + @abstract The locationManager's delegate.
67 + */
68 +@property (nonatomic, weak) NSObject <WLLocationManagerDelegate>*locationManagerDelegate;
69 +
70 +/*!
71 + @property foregroundMode
72 + @abstract The mode of location monitoring while the app is on the foreground.
73 + */
74 +@property (nonatomic) WLLocationForegroundMode foregroundMode;
75 +
76 +/*!
77 + @property backgroundMode
78 + @abstract The mode of location monitoring while the app is on the background or not running.
79 + */
80 +@property (nonatomic) WLLocationForegroundMode backgroundMode;
81 +
82 +/*!
83 + @property geofencingEnabled
84 + @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.
85 + */
86 +@property (nonatomic) BOOL geofencingEnabled;
87 +
88 +/*!
89 + @methodgroup Purpose of Location Manager
90 + */
91 +/*!
92 + This method returns a string which is the Location Manager purpose.
93 + @return Returns location manager purpose.
94 + */
95 +- (NSString *)purpose;
96 +/*!
97 + This method sets Location Manager purpose.
98 + @param purpose A string object with purpose of Location Manager.
99 + */
100 +- (void)setPurpose:(NSString*)purpose;
101 +
102 +/*!
103 + @methodgroup Managing Location Reporting
104 + */
105 +
106 +/*!
107 + @methodgroup Managing AppLifecycle Location Reporting
108 + @description These methods are called during the AppLifecycle.
109 + */
110 +
111 +/*!
112 + This method starts location reporting. It is called when application becomes
113 + active.
114 + */
115 +- (void)applicationDidBecomeActive;
116 +
117 +- (void)sendLocation:(CLLocation *)location;
118 +
119 +/*!
120 + This method stops location reporting. It is called when application enters
121 + background.
122 + */
123 +- (void)applicationDidEnterBackground;
124 +
125 +@end
126 +
127 +@protocol WLLocationManagerDelegate <NSObject>
128 +
129 +- (void)locationManager:(CLLocationManager *)manager
130 + didUpdateToLocation:(CLLocation *)newLocation
131 + fromLocation:(CLLocation *)oldLocation;
132 +
133 +- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region;
134 +
135 +@end
1 +/*
2 + Copyright 2010-2016 Warply Inc. All rights reserved.
3 +
4 + Redistribution and use in source and binary forms, without modification,
5 + are permitted provided that the following conditions are met:
6 +
7 + 1. Redistributions of source code must retain the above copyright notice, this
8 + list of conditions and the following disclaimer.
9 +
10 + 2. Redistributions in binaryform must reproduce the above copyright notice,
11 + this list of conditions and the following disclaimer in the documentation
12 + and/or other materials provided with the distribution.
13 +
14 + THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 + EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 + */
25 +
26 +#import "WLLocationManager.h"
27 +#import "WLGlobals.h"
28 +#import "WLEvent.h"
29 +#import "Warply.h"
30 +#include <math.h>
31 +
32 +#define kGeofencingRadious 300
33 +#define WLDefaultDistanceFilter 200
34 +
35 +@interface WLLocationManager()
36 +{
37 + BOOL even;
38 + double speed;
39 +}
40 +@end
41 +
42 +@implementation WLLocationManager
43 +
44 +@synthesize locationManager = _locationManager;
45 +
46 +#pragma mark - Initialization
47 +///////////////////////////////////////////////////////////////////////////////
48 +- (id)init
49 +{
50 + self = [super init];
51 + if (self) {
52 + // 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
53 +
54 + // initialize locationManager
55 + _locationManager = [[CLLocationManager alloc] init];
56 + _locationManager.delegate = self;
57 +
58 + if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
59 + [self.locationManager requestAlwaysAuthorization];
60 + }
61 +
62 + NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
63 + if ([defaults objectForKey:WL_IOS_LOCATION_FOREGROUND_MODE] != nil) {
64 + // if the setting has already been set in the past, use this value
65 + _foregroundMode = (int)[defaults integerForKey:WL_IOS_LOCATION_FOREGROUND_MODE];
66 + }
67 + else {
68 + //otherwise use the default value
69 + _foregroundMode = WLLocationModeOff;
70 + }
71 +
72 + if ([defaults objectForKey:WL_IOS_LOCATION_BACKGROUND_MODE] != nil) {
73 + // if the setting has already been set in the past, use this value
74 + _backgroundMode = (int)[defaults integerForKey:WL_IOS_LOCATION_BACKGROUND_MODE];
75 + }
76 + else {
77 + //otherwise use the default value
78 + _backgroundMode = WLLocationModeOff;
79 + }
80 +
81 + if ([defaults objectForKey:WL_IOS_GEOFENCING_ENABLED] != nil) {
82 + // if the setting has already been set in the past, use this value
83 + _geofencingEnabled = [defaults boolForKey:WL_IOS_GEOFENCING_ENABLED];
84 + }
85 + else {
86 + //otherwise use the default value
87 + _geofencingEnabled = NO;
88 + }
89 +
90 +
91 + if ([defaults objectForKey:WL_IOS_FOREGROUND_DISTANCE_FILTER] != nil) {
92 + // if the setting has already been set in the past, use this value
93 + _locationManager.distanceFilter = [defaults doubleForKey:WL_IOS_BACKGROUND_DISTANCE_FILTER];
94 + }
95 + else {
96 + //otherwise use the default value
97 + _locationManager.distanceFilter = WLDefaultDistanceFilter;
98 + }
99 +
100 + if ([defaults objectForKey:WL_IOS_LOCATION_BACKGROUND_DESIRED_ACCURACY] != nil) {
101 + // if the setting has already been set in the past, use this value
102 + _locationManager.desiredAccuracy = [defaults doubleForKey:WL_IOS_LOCATION_BACKGROUND_DESIRED_ACCURACY];
103 + }
104 +
105 + switch (self.backgroundMode) {
106 + case WLLocationModeSignificant:
107 + [_locationManager startMonitoringSignificantLocationChanges];
108 + break;
109 + case WLLocationModeStandard:
110 + [_locationManager startUpdatingLocation];
111 + break;
112 + default:
113 + break;
114 + }
115 + }
116 + return self;
117 +}
118 +
119 +#pragma mark - Properties
120 +///////////////////////////////////////////////////////////////////////////////
121 +- (NSString*)purpose
122 +{
123 + if ([_locationManager respondsToSelector:@selector(purpose)]) {
124 + return [_locationManager performSelector:@selector(purpose)];
125 + }
126 + return nil;
127 +}
128 +
129 +///////////////////////////////////////////////////////////////////////////////
130 +- (void)setPurpose:(NSString *)purpose
131 +{
132 + if ((purpose != (NSString *)[NSNull null]) && (purpose.length > 0))
133 + [_locationManager performSelector:@selector(setPurpose:) withObject:purpose];
134 +}
135 +
136 +#pragma mark - Application Lifecycle
137 +///////////////////////////////////////////////////////////////////////////////
138 +- (void)applicationDidBecomeActive
139 +{
140 + // When initializing we use WL_IOS_BACKGROUND_DISTANCE_FILTER and if the app becomes active we reset distanceFilter to WL_IOS_FOREGROUND_DISTANCE_FILTER
141 + NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
142 + _locationManager.distanceFilter = [defaults doubleForKey:WL_IOS_FOREGROUND_DISTANCE_FILTER];
143 + _locationManager.desiredAccuracy = [defaults doubleForKey:WL_IOS_LOCATION_FOREGROUND_DESIRED_ACCURACY];
144 +
145 + switch (_foregroundMode) {
146 + case WLLocationModeOff:
147 + [_locationManager stopUpdatingLocation];
148 + [_locationManager stopMonitoringSignificantLocationChanges];
149 + break;
150 + case WLLocationModeSignificant:
151 + [_locationManager startMonitoringSignificantLocationChanges];
152 + [_locationManager stopUpdatingLocation];
153 + break;
154 + case WLLocationModeStandard:
155 + [_locationManager startUpdatingLocation];
156 + [_locationManager stopMonitoringSignificantLocationChanges];
157 + [self removeGeofences];
158 + }
159 +
160 + if (self.geofencingEnabled) {
161 + [self sendLocation:_locationManager.location];
162 + }
163 + else [self removeGeofences];
164 +}
165 +
166 +///////////////////////////////////////////////////////////////////////////////
167 +- (void)applicationDidEnterBackground
168 +{
169 + if (self.geofencingEnabled) {
170 + [self sendLocation:_locationManager.location];
171 + }
172 + else {
173 + [self removeGeofences];
174 + }
175 +
176 + switch (_backgroundMode) {
177 + case WLLocationModeOff:
178 + [_locationManager stopUpdatingLocation];
179 + [_locationManager stopMonitoringSignificantLocationChanges];
180 + break;
181 + case WLLocationModeSignificant:
182 + [_locationManager startMonitoringSignificantLocationChanges];
183 + [_locationManager stopUpdatingLocation];
184 + break;
185 + case WLLocationModeStandard:
186 + [_locationManager startUpdatingLocation];
187 + _locationManager.distanceFilter = [[NSUserDefaults standardUserDefaults] doubleForKey:@"IOS_BACKGROUND_DISTANCE_FILTER"];
188 + [_locationManager stopMonitoringSignificantLocationChanges];
189 + [self removeGeofences];
190 + }
191 +}
192 +
193 +#pragma mark - Private Methods
194 +///////////////////////////////////////////////////////////////////////////////
195 +- (void)sendLocation:(CLLocation *)location
196 +{
197 + if (location == nil) {
198 + return;
199 + }
200 +
201 + if ([[NSUserDefaults standardUserDefaults] objectForKey:GEOFENCING_POIS_ENABLED] != nil) {
202 + if ([[NSUserDefaults standardUserDefaults] boolForKey:GEOFENCING_POIS_ENABLED]) {
203 + if (![[Warply sharedService] checkIfUserLoactionIsInPois:location])
204 + return;
205 + }
206 + }
207 +
208 + NSDictionary *geofencing = [NSDictionary dictionaryWithObjectsAndKeys:@"tracking", @"action",
209 + [NSNumber numberWithDouble:location.coordinate.latitude], @"lat",
210 + [NSNumber numberWithDouble:location.coordinate.longitude], @"lon",
211 + nil];
212 + NSDictionary *context = [NSDictionary dictionaryWithObject:geofencing forKey:@"geofencing"];
213 +
214 + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:context options:0 error:NULL];
215 +
216 + [[Warply sharedService] sendContext:jsonData successBlock:^(NSDictionary *context) {
217 + NSArray *regionsDicts = [context valueForKey:@"MAPP_GEOFENCING"];
218 +
219 + if (![self canUseLocation] || regionsDicts.count == 0 || _geofencingEnabled == NO)
220 + return;
221 +
222 + NSMutableArray *regions = [NSMutableArray array];
223 + [self removeGeofences];
224 + for (NSDictionary *regionDict in regionsDicts) {
225 + CLCircularRegion *region = [[CLCircularRegion alloc] initWithCenter:CLLocationCoordinate2DMake([[regionDict valueForKey:@"lat"] doubleValue], [[regionDict valueForKey:@"lon"] doubleValue])
226 + radius:fmin(_locationManager.maximumRegionMonitoringDistance, [[regionDict valueForKey:@"radius"] doubleValue])
227 + identifier:[regionDict valueForKey:@"name"]];
228 +
229 + [_locationManager startMonitoringForRegion:region];
230 + [regions addObject:region];
231 + }
232 + } failureBlock:nil];
233 +}
234 +
235 +#pragma mark - CLLocationManagerDelegate
236 +///////////////////////////////////////////////////////////////////////////////
237 +- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
238 +{
239 + switch (status) {
240 + case kCLAuthorizationStatusAuthorizedAlways:
241 + break;
242 + case kCLAuthorizationStatusNotDetermined:
243 + break;
244 + case kCLAuthorizationStatusDenied:
245 + break;
246 + case kCLAuthorizationStatusRestricted:
247 + break;
248 + default:
249 + break;
250 + }
251 +}
252 +
253 +///////////////////////////////////////////////////////////////////////////////
254 +- (void)locationManager:(CLLocationManager *)manager
255 + didFailWithError:(NSError *)error { }
256 +
257 +///////////////////////////////////////////////////////////////////////////////////////////////////
258 +- (void)locationManager:(CLLocationManager *)manager
259 + didUpdateToLocation:(CLLocation *)newLocation
260 + fromLocation:(CLLocation *)oldLocation
261 +{
262 + if (CLLocationCoordinate2DIsValid(newLocation.coordinate) == NO)
263 + return;
264 +
265 + // test the age of the location measurement to determine if the measurement is cached
266 + // in most cases you will not want to rely on cached measurements
267 + NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];
268 + if (locationAge > 5.0) return;
269 +
270 + speed = newLocation.speed;
271 + if (self.locationManagerDelegate != nil && [self.locationManagerDelegate respondsToSelector:@selector(locationManager:didUpdateToLocation:fromLocation:)]) {
272 + NSMethodSignature *sgn = [self methodSignatureForSelector:@selector(locationManager:didUpdateToLocation:fromLocation:)];
273 + NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sgn];
274 + [invocation setTarget:self.locationManagerDelegate];
275 + [invocation setSelector:@selector(locationManager:didUpdateToLocation:fromLocation:)];
276 + [invocation setArgument:&manager atIndex:2];
277 + [invocation setArgument:&newLocation atIndex:3];
278 + [invocation setArgument:&oldLocation atIndex:4];
279 + [invocation invoke];
280 + }
281 +
282 + [self sendLocation:newLocation];
283 +
284 + NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
285 + NSDate *lastFeaturesUpdate = [defaults objectForKey:@"lastFeaturesUpdateTimestamp"];
286 + if ([[NSDate date] timeIntervalSinceDate:lastFeaturesUpdate] > [[defaults valueForKey:@"FEATURES_CHECK_INTERVAL"] intValue]) {
287 + [[Warply sharedService] getAppSettingsWithSuccessBlock:nil failureBlock:nil];
288 + }
289 +}
290 +
291 +///////////////////////////////////////////////////////////////////////////////////////////////////
292 +- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region
293 +{
294 + [self.locationManagerDelegate locationManager:manager didEnterRegion:region];
295 + [self sendLocation:[[CLLocation alloc] initWithLatitude:((CLCircularRegion *)region).center.latitude longitude:((CLCircularRegion *)region).center.longitude]];
296 +}
297 +
298 +- (void)locationManager:(CLLocationManager *)manager monitoringDidFailForRegion:(CLRegion *)region withError:(NSError *)error
299 +{
300 + WLLOG(@"geofencing error: %@", error.localizedDescription);
301 +}
302 +
303 +- (void)removeGeofences
304 +{
305 + for (CLRegion *region in _locationManager.monitoredRegions) {
306 + [_locationManager stopMonitoringForRegion:region];
307 + }
308 +}
309 +
310 +- (BOOL) canUseLocation{
311 +
312 + CLAuthorizationStatus authStatus = [CLLocationManager authorizationStatus];
313 +
314 + if([[UIDevice currentDevice].systemVersion floatValue] >= 8.0)
315 + {
316 + if ([CLLocationManager locationServicesEnabled] &&
317 + ((authStatus == kCLAuthorizationStatusAuthorizedAlways) ||
318 + (authStatus == kCLAuthorizationStatusAuthorizedWhenInUse) ||
319 + ((authStatus == kCLAuthorizationStatusNotDetermined))))
320 + return YES;
321 +
322 + return NO;
323 + }
324 +
325 + if ([CLLocationManager locationServicesEnabled] && [self canUseLocation])
326 + return YES;
327 +
328 + return NO;
329 +
330 +}
331 +
332 +#pragma mark - Memory Management
333 +///////////////////////////////////////////////////////////////////////////////
334 +- (void)dealloc
335 +{
336 + _locationManager.delegate = nil;
337 +}
338 +
339 +@end
1 +/*
2 + Copyright 2010-2016 Warply Inc. All rights reserved.
3 +
4 + Redistribution and use in source and binary forms, without modification,
5 + are permitted provided that the following conditions are met:
6 +
7 + 1. Redistributions of source code must retain the above copyright notice, this
8 + list of conditions and the following disclaimer.
9 +
10 + 2. Redistributions in binaryform must reproduce the above copyright notice,
11 + this list of conditions and the following disclaimer in the documentation
12 + and/or other materials provided with the distribution.
13 +
14 + THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 + EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 + */
25 +
26 +/*!
27 + @header WLPushManager.h
28 + The Push Manager provides a functional interface for handling push notifications.
29 + @copyright Warply Inc.
30 + */
31 +
32 +@import UIKit;
33 +#import <Foundation/Foundation.h>
34 +#import "WLBaseItem.h"
35 +#import "WLInboxItem.h"
36 +#import <UserNotifications/UserNotifications.h>
37 +
38 +@class Warply;
39 +@protocol WLCustomPushHandler;
40 +
41 +/*!
42 + @typedef WLApplicationState
43 + @abstract States in which the app can receive a remote push notification.
44 + @field WLApplicationStateActive The application is running in the foreground and currently receiving events.
45 + @field WLApplicationStateClosed The application is closed.
46 + @field WLApplicationStateBackground The application is running in the background.
47 + */
48 +typedef enum WLApplicationState : unsigned int{
49 + WLApplicationStateActive,
50 + WLApplicationStateClosed,
51 + WLApplicationStateBackground
52 +}WLApplicationState;
53 +
54 +/*!
55 + @class WLUserManager
56 + @discussion This manager handles the Remote Notifications (Push) functionality
57 + 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.
58 + */
59 +@interface WLPushManager : NSObject <UNUserNotificationCenterDelegate>
60 +{
61 + //Settings
62 + NSString *_deviceToken;
63 +}
64 +
65 +/*!
66 + @property hasSentDeviceInfo.
67 + @abstract Returns YES if the device info/application data has been sent during this session.
68 + */
69 +@property (nonatomic) BOOL hasSentDeviceInfo;
70 +
71 +/*!
72 + @property isMissingDeviceInfo.
73 + @abstract Returns YES if the device info/application data has been sent during this session.
74 + */
75 +@property (nonatomic) BOOL isMissingDeviceInfo;
76 +
77 +/*!
78 + @property deviceToken
79 + @abstract The device token property.
80 + */
81 +@property (nonatomic, readonly) NSString *deviceToken;
82 +
83 +
84 +/*!
85 + @property notificationTypes
86 + @abstract A UIRemoteNotificationType property.
87 + */
88 +#pragma clang diagnostic push
89 +#pragma clang diagnostic ignored "-Wdeprecated-declarations"
90 +@property (nonatomic, readonly) UIRemoteNotificationType notificationTypes;
91 +#pragma clang diagnostic pop
92 +
93 +@property (nonatomic, readonly) UNAuthorizationOptions notificationOptions;
94 +
95 +/*!
96 + @property pendingItem
97 + @abstract The remote notification as a WLBaseItem currently stored for later use.
98 + */
99 +@property (nonatomic, strong) WLBaseItem *pendingItem;
100 +
101 +/*!
102 + @property customPushHanlder
103 + @abstract A WLConsumer Manager for handling user name,e-mail and MSISDN.
104 + @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.
105 + */
106 +@property (nonatomic, weak) id <WLCustomPushHandler> customPushHanlder;
107 +
108 +/*!
109 + @methodgroup Registering for Remote Notifications
110 + */
111 +/*!
112 + @abstract Types of Remote Notification.
113 + @discussion This method informs the Warply service for which kind of notification
114 + type the applications need to receive (ex. sound or bagde only etc).
115 + @param types One or many UIRemoteNotificationType
116 + @deprecated This method has been deprecated. Use registerForRemoteNotifications instead.
117 + */
118 +
119 +#pragma clang diagnostic push
120 +#pragma clang diagnostic ignored "-Wdeprecated-declarations"
121 +- (void)registerForRemoteNotificationTypes:(UIRemoteNotificationType)types;
122 +#pragma clang diagnostic pop
123 +/*!
124 + @discussion This method informs the Warply service for which kind of notification
125 + type the applications need to receive (ex. sound or bagde only etc).
126 + */
127 +- (void)registerForRemoteNotifications;
128 +
129 +/*!
130 + @abstract Device Registered for Remote Notifications.
131 + @discussion This method notifies that the device is registered successfully with
132 + APNS for Remote Notifications and sends its token to Warply service.
133 + @param deviceToken The device informations in NSData format.
134 + */
135 +- (void)didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken;
136 +/*!
137 + @abstract Device Failed to Registered for Remote Notifications.
138 + @discussion This method notifies that the device failed to register with APNS
139 + for Remote Notifications and sends its token to Warply service.
140 + @param error An NSError object that encapsulates information why registration did not succeed.
141 + */
142 +- (void)didFailToRegisterForRemoteNotificationsWithError:(NSError *)error;
143 +
144 +/*!
145 + @methodgroup Mananging Received Pushes
146 + */
147 +/*!
148 + @abstract Application Launched due to a Remote Notification.
149 + @discussion This method notifies the WLPushManager that application was launched
150 + and the pass the launch options.
151 + @param launchOptions A dictionary with the application launch options. May be
152 + empty if application launched by user.
153 + */
154 +- (void)didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;
155 +/*!
156 + @abstract Application Received a Remote Notification
157 + @discussion If the application is running and receives a remote notification, this method is called to process the remote notification.
158 + @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.
159 + @param state the state that the app was in at the time it received the push notification.
160 + @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.
161 + */
162 +- (void)didReceiveRemoteNotification:(NSDictionary *)userInfo whileAppWasInState:(WLApplicationState)state;
163 +
164 +/*!
165 + @abstract Application received a Remote Notification.
166 + @discussion This method notifies the WLPushManager that a remote notification was received and passes the data to the didReceiveRemoteNotification:whileAppWasInState: method
167 + @param userInfo The NSDictionary data that contains the remote notification that was received.
168 + */
169 +- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo;
170 +
171 +/*!
172 + @methodgroup Mananging Notifications Badge
173 + */
174 +/*!
175 + @abstract Reset notifications badge.
176 + @discussion This method resets the notification badge to zero.
177 + */
178 +- (void)resetBadge;
179 +
180 +/*!
181 + @methodgroup Handling Pending Notifications
182 + */
183 +/*!
184 + @abstract Handles the pending notification item if it exists.
185 + @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.
186 + @seealso
187 + */
188 +- (BOOL)handlePendingNotification;
189 +
190 +/*!
191 + @abstract Displays displays modally a mini browser with the warp offer.
192 + @param item A WLInboxItem object representation of an offer.
193 + */
194 +- (void)showItem:(WLInboxItem*)item;
195 +
196 +/*!
197 + @methodgroup Handling Device Information
198 + */
199 +/*!
200 + @abstract Sends the application and device information.
201 + @discussion This function is internal and only used by Warply service.
202 + */
203 +- (void)sendDeviceInfoIfNecessary;
204 +
205 +- (void)sendDeviceInfo;
206 +
207 +- (NSDictionary *)deviceInfo;
208 +
209 +- (NSDictionary *)applicationData;
210 +
211 +@end
212 +
213 +/*!
214 + @protocol WLCustomPushHandler
215 + @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.
216 + */
217 +/*!
218 + @methodgroup Handling Custom Push Notifications
219 + */
220 +/*!
221 + @abstract Handles a remote notification that is not of the default warply type (action .
222 + @discussion The default implemention calls showItem: and displays modally a mini browser with the warp offer.
223 + @seealso
224 + */
225 +@protocol WLCustomPushHandler <NSObject>
226 +
227 +- (void)didReceiveRemoteNotification:(NSDictionary *)userInfo whileAppWasInState:(WLApplicationState)state;
228 +
229 +@end
1 +/*
2 + Copyright 2010-2016 Warply Inc. All rights reserved.
3 +
4 + Redistribution and use in source and binary forms, without modification,
5 + are permitted provided that the following conditions are met:
6 +
7 + 1. Redistributions of source code must retain the above copyright notice, this
8 + list of conditions and the following disclaimer.
9 +
10 + 2. Redistributions in binaryform must reproduce the above copyright notice,
11 + this list of conditions and the following disclaimer in the documentation
12 + and/or other materials provided with the distribution.
13 +
14 + THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 + EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 + */
25 +
26 +#import "WLPushManager.h"
27 +#import "WLGlobals.h"
28 +#import "WLEvent.h"
29 +#import "Warply.h"
30 +#import "WLBaseItem.h"
31 +#import <CoreTelephony/CTTelephonyNetworkInfo.h>
32 +#import <CoreTelephony/CTCarrier.h>
33 +#import "WLInboxItem.h"
34 +#import "WLInboxItemViewController.h"
35 +#import <AdSupport/AdSupport.h>
36 +#import "WLUtils.h"
37 +#import "UIViewController+WLAdditions.h"
38 +
39 +///////////////////////////////////////////////////////////////////////////////
40 +@interface WLPushManager()
41 +{
42 + //Push
43 + NSMutableDictionary *_actionHandlerDict;
44 +}
45 +
46 +@property (nonatomic) BOOL apsRegistrationError;
47 +
48 +- (BOOL)isJailBroken;
49 +
50 +@end
51 +
52 +@implementation WLPushManager
53 +
54 +@synthesize deviceToken = _deviceToken;
55 +@synthesize notificationTypes = _notificationTypes;
56 +@synthesize notificationOptions = _notificationOptions;
57 +
58 +///////////////////////////////////////////////////////////////////////////////
59 +static const char* jailbreak_apps[] =
60 +{
61 + "/Applications/Cydia.app",
62 + "/Applications/limera1n.app",
63 + "/Applications/greenpois0n.app",
64 + "/Applications/blackra1n.app",
65 + "/Applications/blacksn0w.app",
66 + "/Applications/redsn0w.app",
67 + NULL,
68 +};
69 +
70 +#pragma mark - Initialization
71 +///////////////////////////////////////////////////////////////////////////////
72 +- (id)init
73 +{
74 + self = [super init];
75 + if (self) {
76 + _actionHandlerDict = [[NSMutableDictionary alloc] init];
77 +#pragma clang diagnostic push
78 +#pragma clang diagnostic ignored "-Wdeprecated-declarations"
79 + _notificationTypes = UIRemoteNotificationTypeNone;
80 +#pragma clang diagnostic pop
81 + _apsRegistrationError = FALSE;
82 + }
83 + return self;
84 +}
85 +
86 +#pragma mark - Properties
87 +///////////////////////////////////////////////////////////////////////////////
88 +- (void)setDeviceToken:(NSString *)aDeviceToken
89 +{
90 + if ([_deviceToken isEqualToString:aDeviceToken] == YES)
91 + return;
92 +
93 + _deviceToken = [aDeviceToken copy];
94 +
95 + //Save new valuetodo
96 + if ((_deviceToken != (NSString *)[NSNull null]) && (_deviceToken.length > 0))
97 + [WLKeychain setString:_deviceToken forKey:@"NBDeviceToken"];
98 + else
99 + [WLKeychain deleteStringForKey:@"NBDeviceToken"];
100 +}
101 +
102 +#pragma mark - Public Methods
103 +///////////////////////////////////////////////////////////////////////////////
104 +#pragma clang diagnostic push
105 +#pragma clang diagnostic ignored "-Wdeprecated-declarations"
106 +- (void)registerForRemoteNotificationTypes:(UIRemoteNotificationType)types
107 +{
108 + if (!SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
109 + _notificationTypes = types;
110 +
111 +
112 + if ([[UIApplication sharedApplication] respondsToSelector:@selector(isRegisteredForRemoteNotifications)])
113 + {
114 + // iOS 8 Notifications
115 + [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
116 +
117 + [[UIApplication sharedApplication] registerForRemoteNotifications];
118 + }
119 + else
120 + {
121 + #pragma clang diagnostic push
122 + #pragma clang diagnostic ignored "-Wdeprecated-declarations"
123 + [[UIApplication sharedApplication] registerForRemoteNotificationTypes:_notificationTypes];
124 + #pragma clang diagnostic pop
125 + }
126 + }
127 +}
128 +#pragma clang diagnostic pop
129 +
130 +//Called when a notification is delivered to a foreground app.
131 +-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{
132 + NSLog(@"User Info : %@",notification.request.content.userInfo);
133 + WLApplicationState warplyAppState;
134 + if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
135 + warplyAppState = WLApplicationStateActive;
136 + [self didReceiveRemoteNotification:notification.request.content.userInfo whileAppWasInState:warplyAppState];
137 + } else {
138 + completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge);
139 + }
140 +}
141 +
142 +//Called to let your app know which action was selected by the user for a given notification.
143 +-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler{
144 + NSString *category = response.notification.request.content.userInfo[@"aps"][@"category"];
145 +
146 + if (category != [NSNull null] && [category isEqualToString:@"shareCategory"]) {
147 + if ([response.actionIdentifier isEqualToString:@"share_identifier"]) {
148 + NSString *title = response.notification.request.content.userInfo[@"data"][@"text"];
149 + NSString *url = response.notification.request.content.userInfo[@"data"][@"url"];
150 +
151 + [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"SharedCategory"];
152 + [[NSUserDefaults standardUserDefaults] setObject:title forKey:@"SharedTitle"];
153 + [[NSUserDefaults standardUserDefaults] setObject:url forKey:@"SharedUrl"];
154 +
155 + [[NSUserDefaults standardUserDefaults] synchronize];
156 + }
157 + } else if (category != [NSNull null] && [category isEqualToString:@"favoriteCategory"]) {
158 + if ([response.actionIdentifier isEqualToString:@"favorite_identifier"]) {
159 + NSLog(@"favorite_identifier");
160 + }
161 + } else if (category != [NSNull null] && [category isEqualToString:@"bookCategory"]) {
162 + if ([response.actionIdentifier isEqualToString:@"book_identifier"]) {
163 + NSString *bookID = response.notification.request.content.userInfo[@"data"][@"id"];
164 +
165 + [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"BookCategory"];
166 + [[NSUserDefaults standardUserDefaults] setObject:bookID forKey:@"BookID"];
167 +
168 + [[NSUserDefaults standardUserDefaults] synchronize];
169 + }
170 + }
171 +
172 + [[NSNotificationCenter defaultCenter] postNotificationName:@"DidReceiveNotificaitonWithAction" object:nil];
173 +
174 + WLApplicationState warplyAppState;
175 + if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive)
176 + warplyAppState = WLApplicationStateActive;
177 + else
178 + warplyAppState = WLApplicationStateBackground;
179 +
180 + [self didReceiveRemoteNotification:response.notification.request.content.userInfo whileAppWasInState:warplyAppState];
181 + completionHandler();
182 +}
183 +
184 +- (void)registerForRemoteNotifications{
185 +
186 + if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
187 + _notificationOptions = UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge;
188 +
189 + UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
190 + center.delegate = self;
191 + [center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error){
192 + if(!error){
193 + [[UIApplication sharedApplication] registerForRemoteNotifications];
194 +
195 + }
196 + }];
197 + } else {
198 + if ([[UIApplication sharedApplication] respondsToSelector:@selector(isRegisteredForRemoteNotifications)])
199 + {
200 + // iOS 8 Notifications
201 + _notificationTypes = UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge;
202 +
203 + [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
204 +
205 + [[UIApplication sharedApplication] registerForRemoteNotifications];
206 + }
207 + else
208 + {
209 + #pragma clang diagnostic push
210 + #pragma clang diagnostic ignored "-Wdeprecated-declarations"
211 + _notificationTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound |UIRemoteNotificationTypeAlert;
212 + [[UIApplication sharedApplication] registerForRemoteNotificationTypes:_notificationTypes];
213 + #pragma clang diagnostic pop
214 + }
215 + }
216 +}
217 +
218 +///////////////////////////////////////////////////////////////////////////////
219 +- (void)didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
220 +{
221 + WLLOG(@"LAUNCH OPTIONS: %@", launchOptions);
222 + NSDictionary *payload = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
223 + if (payload == nil)
224 + return;
225 + if ([payload valueForKey:@"_a"] == nil) {
226 + // The push was sent from another push service
227 + return;
228 + }
229 +
230 + [self didReceiveRemoteNotification:payload whileAppWasInState:WLApplicationStateClosed];
231 +}
232 +
233 +///////////////////////////////////////////////////////////////////////////////
234 +- (void)didReceiveRemoteNotification:(NSDictionary *)userInfo whileAppWasInState:(WLApplicationState)state
235 +{
236 + if ([userInfo valueForKey:@"_a"] == nil) {
237 + // The push was sent from another push service
238 + return;
239 + }
240 +
241 + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:userInfo options:NSJSONWritingPrettyPrinted error:nil];
242 + NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
243 + WLLOG(@"Did receive push: %@", jsonString);
244 + WLInboxItem *inboxItem = [[WLInboxItem alloc] initWithAttributes:userInfo] ;
245 +// [WLAnalyticsManager logUserReceivedPush:inboxItem];
246 +
247 + if (state != WLApplicationStateActive) {
248 + [WLAnalyticsManager logUserEngagedPush:inboxItem];
249 + }
250 +
251 + if (inboxItem.action != 0) {
252 + [self.customPushHanlder didReceiveRemoteNotification:userInfo whileAppWasInState:state];
253 + return;
254 + }
255 + switch (state) {
256 + case WLApplicationStateActive:
257 + {
258 + UIAlertView *alert = [[UIAlertView alloc] init];
259 + [alert setTitle:[[userInfo objectForKey:@"aps"] objectForKey:@"alert"]];
260 + [alert addButtonWithTitle:NSLocalizedString(@"Close", @"Warply")];
261 + [alert addButtonWithTitle:NSLocalizedString(@"View", @"Warply")];
262 + [alert setDelegate:self];
263 + [alert show];
264 +
265 + self.pendingItem = inboxItem;
266 + break;
267 + }
268 + case WLApplicationStateBackground:
269 + {
270 + [self showItem:inboxItem];
271 + break;
272 + }
273 + case WLApplicationStateClosed:
274 + self.pendingItem = inboxItem;
275 + break;
276 + }
277 +}
278 +
279 +///////////////////////////////////////////////////////////////////////////////
280 +- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
281 +{
282 + WLApplicationState warplyAppState;
283 + if (application.applicationState == UIApplicationStateActive)
284 + warplyAppState = WLApplicationStateActive;
285 + else
286 + warplyAppState = WLApplicationStateBackground;
287 + [self didReceiveRemoteNotification:userInfo whileAppWasInState:warplyAppState];
288 +}
289 +
290 +///////////////////////////////////////////////////////////////////////////////
291 +- (void)didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
292 +{
293 + WLLOG(@"DEVICE TOKEN: %@", deviceToken);
294 +
295 + if (SYSTEM_VERSION_LESS_THAN(@"13.0")) {
296 + self.deviceToken = [[[deviceToken.description stringByReplacingOccurrencesOfString:@"<" withString:@""]
297 + stringByReplacingOccurrencesOfString:@">" withString:@""]
298 + stringByReplacingOccurrencesOfString:@" " withString:@""];
299 + } else {
300 + NSUInteger dataLength = deviceToken.length;
301 +
302 + const unsigned char *dataBuffer = (const unsigned char *)deviceToken.bytes;
303 + NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
304 + for (NSInteger index = 0; index < dataLength; ++index) {
305 + [hexString appendFormat:@"%02x", dataBuffer[index]];
306 + }
307 + self.deviceToken = [hexString copy];
308 + }
309 + [self sendDeviceInfoIfNecessary];
310 +}
311 +
312 +///////////////////////////////////////////////////////////////////////////////
313 +- (void)didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
314 +{
315 + WLLOG(@"DEVICE TOKEN: FAILED. Error:%@", [error localizedDescription]);
316 + self.deviceToken = nil;
317 +
318 + if (error.code == 3000 || error.code == 3010)
319 + self.apsRegistrationError = TRUE;
320 +
321 + [self sendDeviceInfoIfNecessary];
322 +}
323 +
324 +///////////////////////////////////////////////////////////////////////////////
325 +- (void)resetBadge
326 +{
327 + UIApplication *application = [UIApplication sharedApplication];
328 + [application setApplicationIconBadgeNumber:1];
329 + [application setApplicationIconBadgeNumber:0];
330 +}
331 +
332 +///////////////////////////////////////////////////////////////////////////////
333 +- (BOOL)handlePendingNotification
334 +{
335 + if (self.pendingItem == nil)
336 + return NO;
337 +
338 + // make sure you call this in your handler to let the server know the user
339 + // engaged with your notification
340 +
341 + WLInboxItem *inboxItem = [[WLInboxItem alloc] initWithItem:self.pendingItem];
342 + [self showItem:inboxItem];
343 + self.pendingItem = nil;
344 +
345 + return YES;
346 +}
347 +
348 +///////////////////////////////////////////////////////////////////////////////
349 +- (void)sendDeviceInfoIfNecessary
350 +{
351 + NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
352 + if ([defaults boolForKey:@"NBAPPUuidChanged"] == YES) {
353 + [defaults removeObjectForKey:@"device_info"];
354 + [defaults removeObjectForKey:WL_APPLICATION_DATA];
355 + [defaults synchronize];
356 +
357 + }
358 +
359 + NSDictionary *oldDeviceInfo = [defaults objectForKey:@"device_info"];
360 +
361 + BOOL device_info_has_changed = ![[self deviceInfo] isEqualToDictionary:oldDeviceInfo];
362 +
363 + NSDictionary *oldApplicationData = [defaults objectForKey:WL_APPLICATION_DATA];
364 + BOOL application_data_has_changed = ![[self applicationData] isEqualToDictionary:oldApplicationData];
365 +
366 + if (device_info_has_changed || application_data_has_changed || _isMissingDeviceInfo) {
367 + [self sendDeviceInfo];
368 + }
369 +}
370 +
371 +///////////////////////////////////////////////////////////////////////////////
372 +- (void)sendDeviceInfo
373 +{
374 + WLEventSimple *deviceInfoEvent = [[WLEventSimple alloc] initWithType:@"device_info" andContext:[NSDictionary dictionaryWithObject:[self deviceInfo] forKey:@"device_info"]];
375 + [[Warply sharedService] addEvent:(WLEvent*)deviceInfoEvent priority:NO];
376 +
377 + WLEventSimple *applicationDataEvent = [[WLEventSimple alloc] initWithType:WL_APPLICATION_DATA andContext:[NSDictionary dictionaryWithObject:[self applicationData] forKey:WL_APPLICATION_DATA]];
378 + [[Warply sharedService] addEvent:(WLEvent*)applicationDataEvent priority:NO];
379 + _hasSentDeviceInfo = YES;
380 + _isMissingDeviceInfo = NO;
381 + [[Warply sharedService] sendAllEventsWithCompletionBlock:^{
382 + NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
383 + [defaults setObject:[self applicationData] forKey:WL_APPLICATION_DATA];
384 + [defaults setObject:[self deviceInfo] forKey:@"device_info"];
385 + [defaults synchronize];
386 + } failureBlock:nil];
387 +}
388 +
389 +///////////////////////////////////////////////////////////////////////////////
390 +- (void)showItem:(WLInboxItem*)item
391 +{
392 + WLInboxItemViewController *itemViewController = [[WLInboxItemViewController alloc] initWithItem:item];
393 +
394 + UINavigationController *newModalController = [[UINavigationController alloc] initWithRootViewController:itemViewController];
395 +
396 + newModalController.navigationBarHidden = YES;
397 + newModalController.toolbarHidden = NO;
398 +
399 + UIViewController *existingModalController = [[UIApplication sharedApplication].delegate.window.rootViewController topModalViewController];
400 +
401 + if (existingModalController == nil) {
402 + 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];
403 + [alert show];
404 +
405 + return;
406 + }
407 +
408 + [existingModalController presentViewController:newModalController animated:YES completion:nil];
409 +}
410 +
411 +///////////////////////////////////////////////////////////////////////////////
412 +- (NSDictionary *)deviceInfo
413 +{
414 + CTTelephonyNetworkInfo *telephony = [[CTTelephonyNetworkInfo alloc] init];
415 + CTCarrier *carrier = telephony.subscriberCellularProvider;
416 + NSArray *prefLangs = [NSLocale preferredLanguages];
417 + NSUInteger count = [prefLangs count];
418 + NSString *langs = [NSString stringWithFormat:@"%@, %@, %@, %@, %@",
419 + (count > 0)?[prefLangs objectAtIndex:0]:@"-",
420 + (count > 1)?[prefLangs objectAtIndex:1]:@"-",
421 + (count > 2)?[prefLangs objectAtIndex:2]:@"-",
422 + (count > 3)?[prefLangs objectAtIndex:3]:@"-",
423 + (count > 4)?[prefLangs objectAtIndex:4]:@"-"];
424 +
425 + NSMutableDictionary *deviceInfo = [NSMutableDictionary dictionaryWithObjectsAndKeys:
426 +#if (DEBUG == 1)
427 + @"true" , @"development",
428 +#else
429 + @"false" , @"development",
430 +#endif
431 + nil];
432 +
433 + if ([[[UIDevice currentDevice] systemName] length] != 0) {
434 + [deviceInfo setValue:[[UIDevice currentDevice] systemName] forKey:@"ios_system_name"];
435 + }
436 + if ([[[UIDevice currentDevice] systemVersion] length] != 0) {
437 + [deviceInfo setValue:[[UIDevice currentDevice] systemVersion] forKey:@"ios_system_version"];
438 + }
439 + if ([[[UIDevice currentDevice] platformString] length] != 0) {
440 + [deviceInfo setValue:[[UIDevice currentDevice] platformString] forKey:@"ios_model"];
441 + }
442 + if ([[UIDevice currentDevice] platform].length != 0) {
443 + [deviceInfo setValue:[[UIDevice currentDevice] platform] forKey:@"ios_device_model"];
444 + }
445 + if ([[UIDevice currentDevice] deviceFamilyString].length != 0) {
446 + [deviceInfo setValue:[[UIDevice currentDevice] deviceFamilyString] forKey:@"device_family"];
447 + }
448 + if (carrier.carrierName.length != 0) {
449 + [deviceInfo setValue:carrier.carrierName forKey:@"carrier_name"];
450 + }
451 + if (carrier.isoCountryCode.length != 0) {
452 + [deviceInfo setValue:carrier.isoCountryCode forKey:@"ios_iso_country_code"];
453 + }
454 + if ([[[UIDevice currentDevice] localizedModel] length] != 0) {
455 + [deviceInfo setValue:[[UIDevice currentDevice] localizedModel] forKey:@"ios_localized_model"];
456 + }
457 + if ([[[NSLocale currentLocale] localeIdentifier] length] != 0) {
458 + [deviceInfo setValue:[[NSLocale currentLocale] localeIdentifier] forKey:@"ios_locale"];
459 + }
460 + if (langs.length != 0) {
461 + [deviceInfo setValue:langs forKey:@"ios_languages"];
462 + }
463 +
464 + [deviceInfo setValue:@"apple" forKey:@"vendor"];
465 +
466 + [deviceInfo setValue:@"ios" forKey:@"platform"];
467 +
468 + [deviceInfo setValue:[[UIDevice currentDevice] systemVersion] forKey:@"os_version"];
469 +
470 + [deviceInfo setValue:[[[UIDevice currentDevice] identifierForVendor] UUIDString] forKey:@"unique_device_id"];
471 +
472 + [deviceInfo setValue:[[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString] forKey:@"advertising_id"];
473 +
474 + [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"];
475 +
476 +#if (WARPLY_UDID_ENABLED == 1)
477 + if ([[UIDevice currentDevice] respondsToSelector:@selector(uniqueIdentifier)]) {
478 + [device_info setValue:[UIDevice currentDevice].uniqueIdentifier forKey:@"ios_unique_identifier"];
479 + }
480 +#endif
481 +
482 + [deviceInfo setValue:[self isJailBroken]?[NSNumber numberWithBool:YES] : [NSNumber numberWithBool:NO] forKey:@"ios_is_jailbroken_phone"];
483 +
484 + if (_deviceToken.length != 0) {
485 + [deviceInfo setValue:_deviceToken forKey:@"device_token"];
486 + }
487 +
488 + [deviceInfo setValue:[NSNumber numberWithBool:!self.apsRegistrationError] forKey:@"ios_aps_entitlement_valid"];
489 +
490 + NSUInteger rntypes;
491 +
492 + if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
493 + [deviceInfo setValue:[NSNumber numberWithInt:_notificationOptions] forKey:@"notification_types"];
494 + } else {
495 + [deviceInfo setValue:[NSNumber numberWithInt:_notificationTypes] forKey:@"notification_types"];
496 + }
497 +
498 + if (SYSTEM_VERSION_LESS_THAN(@"8.0")) {
499 +#pragma clang diagnostic push
500 +#pragma clang diagnostic ignored "-Wdeprecated-declarations"
501 + rntypes = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
502 +#pragma clang diagnostic pop
503 + }else{
504 + rntypes = [[[UIApplication sharedApplication] currentUserNotificationSettings] types];
505 + }
506 +
507 + [deviceInfo setValue:[NSNumber numberWithInteger:rntypes] forKey:@"user_enabled_notification_types"];
508 +
509 + // NSMutableDictionary *apple_uuids = [NSMutableDictionary dictionaryWithCapacity:2];
510 + [deviceInfo setValue:[NSNumber numberWithBool:[ASIdentifierManager sharedManager].advertisingTrackingEnabled] forKey:@"advertising_tracking_enabled"];
511 + [deviceInfo setValue:[[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString] forKey:@"advertising_identifier"];
512 + [deviceInfo setValue:[[[UIDevice currentDevice] identifierForVendor] UUIDString] forKey:@"identifier_for_vendor"];
513 +
514 + // [deviceInfo setValue:apple_uuids forKey: @"ios_uuids"];
515 +
516 + NSLog(@"%@", deviceInfo);
517 +
518 + return deviceInfo;
519 +}
520 +
521 +///////////////////////////////////////////////////////////////////////////////
522 +- (NSDictionary *)applicationData
523 +{
524 + //Application Data Hack
525 + NSBundle *mainBundle = [NSBundle mainBundle];
526 + NSMutableDictionary *applicationData = [NSMutableDictionary dictionaryWithCapacity:3];
527 +
528 + if ([Warply get].length != 0) {
529 + [applicationData setValue:[Warply get] forKey:@"sdk_version"];
530 + }
531 +
532 + NSString *CFBundleIdentifier = [mainBundle objectForInfoDictionaryKey:@"CFBundleIdentifier"];
533 + if (CFBundleIdentifier.length != 0) {
534 + [applicationData setValue:CFBundleIdentifier forKey:@"bundle_identifier"];
535 + }
536 +
537 + NSString *CFBundleShortVersionString = [mainBundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
538 + if (CFBundleShortVersionString.length != 0) {
539 + [applicationData setValue:CFBundleShortVersionString forKey:@"app_version"];
540 + }
541 +
542 + NSString *CFBundleVersion = [mainBundle objectForInfoDictionaryKey:@"CFBundleVersion"];
543 + if (CFBundleVersion.length != 0) {
544 + [applicationData setValue:CFBundleVersion forKey:@"app_build"];
545 + }
546 + return applicationData;
547 +}
548 +
549 +#pragma mark - Private Methods
550 +///////////////////////////////////////////////////////////////////////////////
551 +- (BOOL)isJailBroken
552 +{
553 + NSDictionary *info = [[NSBundle mainBundle] infoDictionary];
554 +
555 + // 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.
556 + if ([info objectForKey: @"SignerIdentity"] != nil)
557 + return YES;
558 +
559 + // Now check for known jailbreak apps. If we encounter one, the device is jailbroken.
560 + for (int i = 0; jailbreak_apps[i] != NULL; ++i)
561 + {
562 + if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithUTF8String:jailbreak_apps[i]]])
563 + return YES;
564 + }
565 +
566 + return NO;
567 +}
568 +
569 +#pragma mark - UIAlertViewDelegate
570 +///////////////////////////////////////////////////////////////////////////////
571 +- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
572 +{
573 + if (buttonIndex == 1) {
574 + [WLAnalyticsManager logUserEngagedPush:self.pendingItem];
575 + [self handlePendingNotification];
576 + }
577 +}
578 +
579 +@end
1 +/*
2 + Copyright 2010-2016 Warply Inc. All rights reserved.
3 +
4 + Redistribution and use in source and binary forms, without modification,
5 + are permitted provided that the following conditions are met:
6 +
7 + 1. Redistributions of source code must retain the above copyright notice, this
8 + list of conditions and the following disclaimer.
9 +
10 + 2. Redistributions in binaryform must reproduce the above copyright notice,
11 + this list of conditions and the following disclaimer in the documentation
12 + and/or other materials provided with the distribution.
13 +
14 + THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 + EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 + */
25 +
26 +/*!
27 + @header WLUserManager.h
28 + The ConsumerData Manager provides a functional interface for user related data.
29 + Use the methods declared here to get and send user name,email and MSISDN, add tags and connect your CRM id to our data.
30 + @copyright Warply Inc.
31 + */
32 +
33 +#import <Foundation/Foundation.h>
34 +#import "Warply.h"
35 +
36 +/*!
37 + @class WLUserManager
38 + @discussion This manager enables the device and Warply server to exchange info about the user.
39 + */
40 +@interface WLUserManager : NSObject
41 +/*!
42 + @methodgroup Sending User Data
43 + @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.
44 + */
45 +
46 +/*!
47 + @abstract Send user name.
48 + @discussion This class method send user name to Warply service.
49 + @param userName A string object with user name.
50 + */
51 ++ (void)sendName:(NSString *)userName;
52 +/*!
53 + @abstract Send user e-mail.
54 + @discussion This class method send user e-mail to Warply service. Also, make sure
55 + that e-mail is correct format prior sending it.
56 + @param userEmail A string object with user e-mail.
57 + */
58 ++ (void)sendEmail:(NSString *)userEmail;
59 +/*!
60 + @abstract Send user MSISDN.
61 + @discussion This class method send user MSISDN to Warply service.
62 + @param userMsisdn A string object with user msisdn.
63 + */
64 ++ (void)sendMsisdn:(NSString *)userMsisdn;
65 +/*!
66 + @abstract Sends a dictionary to warply containing data related to the user.
67 + @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).
68 + @param customData A dictionary containing custom user data.
69 + */
70 ++ (void)sendCustomData:(NSDictionary *)customData;
71 +/*!
72 + @methodgroup Getting User Data
73 + */
74 +/*!
75 + @abstract Get user name.
76 + @discussion This class method gets user name from Warply service.
77 + @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.
78 + @attributeblock failureBlock This block is called when getUserName fails and returns a NSError object with failure code and description.
79 + */
80 ++ (void)getNameWithSuccessBlock:(void (^)(NSString *userName))success failureBlock:(void (^)(NSError *error))failure;
81 +/*!
82 + @abstract Get user e-mail.
83 + @discussion This class method gets user e-mail from Warply service.
84 + @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.
85 + @attributeblock failureBlock This block is called when getUserEmail fails and returns a NSError object with failure code and description.
86 + */
87 ++ (void)getEmailWithSuccessBlock:(void (^)(NSString *userEmail))success failureBlock:(void (^)(NSError *error))failure;
88 +/*!
89 + @abstract Get user MSISDN.
90 + @discussion This class method gets user MSISDN from Warply service.
91 + @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.
92 + @attributeblock failureBlock This block is called when getUserMsisdn fails and returns a NSError object with failure code and description.
93 + */
94 ++ (void)getMsisdnWithSuccessBlock:(void (^)(NSString *userMsisdn))success failureBlock:(void (^)(NSError *error))failure;
95 +/*!
96 + @abstract Get user custom data.
97 + @discussion This class method gets user MSISDN from Warply service.
98 + @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.
99 + @attributeblock failureBlock This block is called when the call fails and returns a NSError object with failure code and description.
100 + */
101 ++ (void)getCustomDataWithSuccessBlock:(void (^)(NSDictionary *customData))success failureBlock:(void (^)(NSError *error))failure;
102 +/*!
103 + @methodgroup Sending User Advertising IDs
104 + */
105 +/*!
106 + @abstract Send user advertising ids.
107 + @discussion This class method sends both user and vendor adverting identifiers.
108 + These identifiers are available only when user allows ad tracking from the device
109 + settings.
110 + @dependency AdSupport framework (Available on iOS 6 only).
111 + */
112 ++ (void)sendUUIDS;
113 +/*!
114 + @methodgroup Tagging Users
115 + @discusion These methods send user related tags to the warply server. The users can then be targeted based on these tags.
116 + */
117 +/*!
118 + @abstract Adds a single user tag.
119 + @discussion This class method sends a tag to be added in Warply service. This event
120 + is sent immediately.
121 + @param tag A string object with an arbitrary tag.
122 + */
123 ++ (void)addTag:(NSString *)tag;
124 +/*!
125 + @abstract Adds an array of user tags.
126 + @discussion This class method sends an array of tags to be added in Warply service.
127 + This event is sent immediately.
128 + @param tag An array of tags. Each tag must me be a string object.
129 + */
130 ++ (void)addTags:(NSArray *)tags;
131 +
132 +/*!
133 + @abstract Removes the existing tags and adds an array of user tags.
134 + @discussion This class method sends an array of tags to be added in Warply service and replace any existing ones.
135 + This event is sent immediately.
136 + @param tag An array of tags. Each tag must me be a string object.
137 + */
138 ++ (void)rewriteTags:(NSArray *)tags;
139 +
140 +/*!
141 + @methodgroup Removing User Tags
142 + */
143 +/*!
144 + @abstract Remove a single user tag.
145 + @discussion This class method sends a tag to be removed in Warply service. This event
146 + is sent immediately.
147 + @param tag An string object with an arbitrary tag.
148 + */
149 ++ (void)removeTag:(NSString *)tag;
150 +/*!
151 + @abstract Removes an array of user tags.
152 + @discussion This class method sends an array of tags to be removed in Warply service.
153 + This event is sent immediately.
154 + @param tags An array of tags. Each tag must me be a string object.
155 + */
156 ++ (void)removeTags:(NSArray *)tags;
157 +
158 +/*!
159 + @abstract Removes all user tags.
160 + */
161 ++ (void)removeAllTags;
162 +/*!
163 + @methodgroup Getting User Tags
164 + */
165 +/*!
166 + @abstract Get user tags.
167 + @discussion This class method gets all the user tags from the Warply service.
168 + @attributeblock successBlock This block is called when getTags is sucessful and returns a NSArray object with the user tags.
169 + @attributeblock failureBlock This block is called when getTags fails and returns a NSError object that encapsulates information why registration did not succeed.
170 + */
171 ++ (void)getTagsWithSuccessBlock:(void (^)(NSArray *tags))success failureBlock:(void (^)(NSError *error))failure;
172 +
173 +/*!
174 + @methodgroup Creating and Resuming a session
175 + @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.
176 + */
177 +/*!
178 + @abstract Login a user. If no user has been registered with this auth token, the user is being registered.
179 + @discussion This class method logins a user to Warply service. The login is sucessful only if
180 + previously the user is sucesfully registered.
181 + @param authToken User arbitrary time invariant token. Must be the same token used
182 + for registering the user.
183 + @attributeblock success This block is called when sessionLogin is sucessful.
184 + @attributeblock failure This block is called when sessionLogin fails and returns a NSError object with failure code and description.
185 + */
186 ++ (void)sessionLogin:(NSString *)authToken successBlock:(void (^)(void))success failureBlock:(void (^)(void))failure;
187 +/*!
188 + @abstract Logout a user.
189 + @discussion This class method logouts a user to Warply service. The logout is sucessful only if
190 + previously the user is sucesfully registered.
191 + @param authToken User arbitrary time invariant token. Must be the same token used
192 + for registering the user.
193 + @attributeblock success This block is called when sessionLogout is sucessful.
194 + @attributeblock failure This block is called when sessionLogout fails.
195 + */
196 ++ (void)sessionLogout:(NSString *)authToken successBlock:(void (^)(void))success failureBlock:(void (^)(void))failure;
197 +
198 +/*!
199 + @abstract Determine if the user wants to receive or not push notifications from the Warply server.
200 + @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.
201 + @attributeblock success This block is called when the call is sucessful.
202 + @attributeblock failure This block is called when the call fails.
203 + */
204 ++ (void)setWarplyNotificationsEnabled:(BOOL)enable successBlock:(void (^)(void))success failureBlock:(void (^)(NSError *error))failure;
205 +
206 +/*!
207 + @abstract This method retreives from the server the information of whether the user wants to receive Warply notifications or not @see + warplyNotificationsEnabledWithsuccessBlock:failureBlock:
208 + @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.
209 + @attributeblock failure This block is called when the call fails.
210 + */
211 ++ (void)warplyNotificationsEnabledWithsuccessBlock:(void (^)(BOOL isEnabled))success failureBlock:(void (^)(NSError *error))failure;
212 +
213 +@end
1 +/*
2 + Copyright 2010-2016 Warply Inc. All rights reserved.
3 +
4 + Redistribution and use in source and binary forms, without modification,
5 + are permitted provided that the following conditions are met:
6 +
7 + 1. Redistributions of source code must retain the above copyright notice, this
8 + list of conditions and the following disclaimer.
9 +
10 + 2. Redistributions in binaryform must reproduce the above copyright notice,
11 + this list of conditions and the following disclaimer in the documentation
12 + and/or other materials provided with the distribution.
13 +
14 + THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 + EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 + */
25 +
26 +#import "WLUserManager.h"
27 +#import <AdSupport/AdSupport.h>
28 +
29 +@implementation WLUserManager
30 +
31 +#pragma mark - User Data
32 +///////////////////////////////////////////////////////////////////////////////
33 ++ (void)getNameWithSuccessBlock:(void (^)(NSString *userName))success
34 + failureBlock:(void (^)(NSError *error))failure
35 +{
36 + if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_CONSUMER_DATA_ENABLED)) {
37 + return;
38 + }
39 +
40 + [[Warply sharedService] getContextWithPath:@"consumer_data" successBlock:^(NSDictionary *dict){
41 + if (success)
42 + success([dict valueForKey:@"user_name"]);
43 + } failureBlock:^(NSError *error) {
44 + if (failure)
45 + failure(error);
46 + }];
47 +}
48 +
49 +///////////////////////////////////////////////////////////////////////////////
50 ++ (void)getEmailWithSuccessBlock:(void (^)(NSString *userEmail))success
51 + failureBlock:(void (^)(NSError *error))failure
52 +{
53 + if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_CONSUMER_DATA_ENABLED)) {
54 + return;
55 + }
56 +
57 + [[Warply sharedService] getContextWithPath:@"consumer_data" successBlock:^(NSDictionary *dict){
58 + if (success)
59 + success([dict valueForKey:@"user_email"]);
60 + } failureBlock:^(NSError *error) {
61 + if (failure)
62 + failure(error);
63 + }];
64 +}
65 +
66 +///////////////////////////////////////////////////////////////////////////////
67 ++ (void)getMsisdnWithSuccessBlock:(void (^)(NSString *userMsisdn))success
68 + failureBlock:(void (^)(NSError *error))failure
69 +{
70 + if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_CONSUMER_DATA_ENABLED)) {
71 + return;
72 + }
73 +
74 + [[Warply sharedService] getContextWithPath:@"consumer_data" successBlock:^(NSDictionary *dict){
75 + if (success)
76 + success([dict valueForKey:@"msisdn"]);
77 + } failureBlock:^(NSError *error) {
78 + if (failure)
79 + failure(error);
80 + }];
81 +}
82 +
83 ++ (void)getCustomDataWithSuccessBlock:(void (^)(NSDictionary *customData))success
84 + failureBlock:(void (^)(NSError *error))failure
85 +{
86 + if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_CONSUMER_DATA_ENABLED)) {
87 + return;
88 + }
89 +
90 + [[Warply sharedService] getContextWithPath:@"consumer_data" successBlock:^(NSDictionary *dict){
91 + if (success)
92 + success([dict valueForKey:@"custom_data"]);
93 + } failureBlock:^(NSError *error) {
94 + if (failure)
95 + failure(error);
96 + }];
97 +}
98 +
99 +///////////////////////////////////////////////////////////////////////////////
100 ++ (void)sendName:(NSString *)userName
101 +{
102 + [self sendLoginFieldWithName:@"user_name" andValue:userName];
103 +}
104 +
105 +///////////////////////////////////////////////////////////////////////////////
106 ++ (void)sendEmail:(NSString *)userEmail
107 +{
108 + [self sendLoginFieldWithName:@"user_email" andValue:userEmail];
109 +}
110 +
111 +///////////////////////////////////////////////////////////////////////////////
112 ++ (void)sendMsisdn:(NSString *)userMsisdn
113 +{
114 + [self sendLoginFieldWithName:@"msisdn" andValue:userMsisdn];
115 +}
116 +
117 +///////////////////////////////////////////////////////////////////////////////
118 ++ (void)sendLoginFieldWithName:(NSString *)key andValue:(NSString *)value
119 +{
120 + if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_CONSUMER_DATA_ENABLED)) {
121 + return;
122 + }
123 +
124 + NSMutableDictionary *login_data = [NSMutableDictionary dictionaryWithCapacity:1];
125 + if ([value length] > 0)
126 + [login_data setValue:value forKey:key];
127 +
128 + NSDictionary *eventDict = [NSDictionary dictionaryWithObjectsAndKeys:login_data, @"login_data", nil];
129 + WLEventSimple *event = [WLEventSimple eventWithType:@"login_data" andContext:eventDict];
130 + [[Warply sharedService] addEvent:event priority:YES];
131 +}
132 +
133 +///////////////////////////////////////////////////////////////////////////////
134 ++ (void)sendCustomData:(NSDictionary *)customData
135 +{
136 + if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_CONSUMER_DATA_ENABLED)) {
137 + return;
138 + }
139 +
140 + NSMutableDictionary *custom_data = [NSMutableDictionary dictionaryWithCapacity:1];
141 + if (customData != nil)
142 + [custom_data setValue:customData forKey:@"custom_data"];
143 +
144 + NSDictionary *eventDict = [NSDictionary dictionaryWithObjectsAndKeys:custom_data, @"consumer_data", nil];
145 + WLEventSimple *event = [WLEventSimple eventWithType:@"consumer_data" andContext:eventDict];
146 + [[Warply sharedService] addEvent:event priority:YES];
147 +}
148 +
149 +#pragma mark - UUIDs
150 +///////////////////////////////////////////////////////////////////////////////
151 ++ (void)sendUUIDS
152 +{
153 + if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_CONSUMER_DATA_ENABLED)) {
154 + return;
155 + }
156 +
157 + if (SYSTEM_VERSION_LESS_THAN(@"6.0"))
158 + return;
159 +
160 + NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
161 + BOOL uuidsAlreadySentNum = [defaults boolForKey:@"uuidsAlreadySent"];
162 + if (uuidsAlreadySentNum)
163 + return;
164 +
165 + NSMutableDictionary *apple_uuids = [NSMutableDictionary dictionaryWithCapacity:2];
166 + [apple_uuids setValue:[NSNumber numberWithBool:[ASIdentifierManager sharedManager].advertisingTrackingEnabled] forKey:@"advertising_tracking_enabled"];
167 + [apple_uuids setValue:[[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString] forKey:@"advertising_identifier"];
168 + [apple_uuids setValue:[[[UIDevice currentDevice] identifierForVendor] UUIDString] forKey:@"identifier_for_vendor"];
169 + NSDictionary *login_data = [NSDictionary dictionaryWithObjectsAndKeys:apple_uuids, @"ios_uuids", nil];
170 + NSDictionary *eventDict = [NSDictionary dictionaryWithObjectsAndKeys:login_data, @"login_data", nil];
171 + WLEventSimple *event = [WLEventSimple eventWithType:@"login_data" andContext:eventDict];
172 + [[Warply sharedService] addEvent:event priority:NO];
173 + [defaults setBool:YES forKey:@"uuidsAlreadySent"];
174 + [defaults synchronize];
175 +}
176 +
177 +#pragma mark - User Tagging
178 +///////////////////////////////////////////////////////////////////////////////
179 ++ (void)addTag:(NSString *)tag
180 +{
181 + [self addTags:[NSArray arrayWithObject:tag]];
182 +}
183 +
184 +///////////////////////////////////////////////////////////////////////////////
185 ++ (void)addTags:(NSArray *)tags
186 +{
187 + if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_USER_TAGGING_ENABLED)) {
188 + return;
189 + }
190 + //Checking for items that are not NSString type.
191 +#ifdef DEBUG
192 + for (id tag in tags) {
193 + NSAssert([tag isKindOfClass:[NSString class]], @"Array with only NSString objects is allowed in addTags:");
194 + }
195 +#endif
196 +
197 + NSDictionary *eventContext = @{@"tags": @{@"action": @"add_tags", @"tags":tags}};
198 + WLEventSimple *event = [[WLEventSimple alloc] initWithType:@"tags" andContext:eventContext];
199 + [[Warply sharedService] addEvent:event priority:YES];
200 +
201 +}
202 +
203 +///////////////////////////////////////////////////////////////////////////////
204 ++ (void)removeTag:(NSString *)tag
205 +{
206 + [self removeTags:[NSArray arrayWithObject:tag]];
207 +}
208 +
209 +///////////////////////////////////////////////////////////////////////////////
210 ++ (void)removeTags:(NSArray *)tags
211 +{
212 + if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_USER_TAGGING_ENABLED)) {
213 + return;
214 + }
215 +
216 + NSDictionary *eventContext = @{@"tags": @{@"action": @"remove_tags", @"tags":tags}};
217 + //Checking for items that are not NSString type.
218 +#ifdef DEBUG
219 + for (id tag in tags) {
220 + NSAssert([tag isKindOfClass:[NSString class]], @"Array with only NSString objects is allowed in removeTags:");
221 + }
222 +#endif
223 + WLEventSimple *event = [[WLEventSimple alloc] initWithType:@"tags" andContext:eventContext];
224 + [[Warply sharedService] addEvent:event priority:YES];
225 +
226 +}
227 +
228 +///////////////////////////////////////////////////////////////////////////////
229 ++ (void)removeAllTags
230 +{
231 + if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_USER_TAGGING_ENABLED)) {
232 + return;
233 + }
234 + NSDictionary *eventContext = @{@"tags": @{@"action": @"remove_all_tags"}};
235 + //Checking for items that are not NSString type.
236 + WLEventSimple *event = [[WLEventSimple alloc] initWithType:@"tags" andContext:eventContext];
237 + [[Warply sharedService] addEvent:event priority:YES];
238 +
239 +}
240 +
241 +///////////////////////////////////////////////////////////////////////////////
242 ++ (void)rewriteTags:(NSArray *)tags
243 +{
244 + if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_USER_TAGGING_ENABLED)) {
245 + return;
246 + }
247 + //Checking for items that are not NSString type.
248 +#ifdef DEBUG
249 + for (id tag in tags) {
250 + NSAssert([tag isKindOfClass:[NSString class]], @"Array with only NSString objects is allowed in addTags:");
251 + }
252 +#endif
253 +
254 + NSDictionary *eventContext = @{@"tags": @{@"action": @"rewrite_tags", @"tags":tags}};
255 + WLEventSimple *event = [[WLEventSimple alloc] initWithType:@"tags" andContext:eventContext];
256 + [[Warply sharedService] addEvent:event priority:YES];
257 +
258 +}
259 +
260 +///////////////////////////////////////////////////////////////////////////////
261 ++ (void)getTagsWithSuccessBlock:(void (^)(NSArray *tags))success failureBlock:(void (^)(NSError *error))failure
262 +{
263 + if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_USER_TAGGING_ENABLED)) {
264 + return;
265 + }
266 +
267 + [[Warply sharedService] getContextWithPath:@"tags"
268 + successBlock:^(NSArray *tags) {
269 + if (success) {
270 + success(tags);
271 + }
272 + } failureBlock:^(NSError *error) {
273 + if (failure) {
274 + failure(error);
275 + }
276 + }];
277 +}
278 +
279 +#pragma mark - User Session
280 +///////////////////////////////////////////////////////////////////////////////
281 ++ (void)sessionLogin:(NSString *)authToken
282 + successBlock:(void (^)(void))success
283 + failureBlock:(void (^)(void))failure
284 +{
285 + if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_USER_SESSION_ENABLED)) {
286 + return;
287 + }
288 +
289 + if (authToken.length == 0) {
290 + if (failure) {
291 + WLLOG(@"Auth token should not be an empty string or nil;");
292 + failure();
293 + }
294 + }
295 + NSDictionary *userSessionDict = [NSDictionary dictionaryWithObjectsAndKeys:[NSDictionary dictionaryWithObject:authToken forKey:@"auth_token"], @"login", nil];
296 + NSDictionary *postDictionary = [NSDictionary dictionaryWithObjectsAndKeys:userSessionDict, @"user_session", nil];
297 + NSError *error;
298 + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDictionary options:0 error:&error];
299 + if (error) {
300 + WLLOG(@"Invalid auth token");
301 + if (failure) {
302 + failure();
303 + }
304 + return;
305 + }
306 + [[Warply sharedService] sendContext:jsonData successBlock:^(NSDictionary *responseDict) {
307 + if (success)
308 + success();
309 + } failureBlock:^(NSError *error) {
310 + [self sessionRegister:authToken successBlock:success failureBlock:failure];
311 + ;
312 + }];
313 +}
314 +
315 +///////////////////////////////////////////////////////////////////////////////
316 ++ (void)sessionLogout:(NSString *)authToken
317 + successBlock:(void (^)(void))success
318 + failureBlock:(void (^)(void))failure
319 +{
320 + if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_USER_SESSION_ENABLED)) {
321 + return;
322 + }
323 +
324 + if (authToken.length == 0) {
325 + if (failure) {
326 + WLLOG(@"Auth token cannot be nil or empty string.");
327 + failure();
328 + }
329 + return;
330 + }
331 +
332 + NSDictionary *userSessionDict = [NSDictionary dictionaryWithObjectsAndKeys:[NSDictionary dictionaryWithObject:authToken forKey:@"auth_token"], @"logout", nil];
333 + NSDictionary *postDictionary = [NSDictionary dictionaryWithObjectsAndKeys:userSessionDict, @"user_session", nil];
334 +
335 + NSError *error;
336 + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDictionary options:0 error:&error];
337 + if (error != nil) {
338 + WLLOG(@"Invalid auth token");
339 + return;
340 + }
341 + [[Warply sharedService] sendContext:jsonData successBlock:^(NSDictionary *responseDict){
342 + if (success)
343 + success();
344 + } failureBlock:^(NSError *error){
345 + if (failure)
346 + failure();
347 + }];
348 +}
349 +
350 +///////////////////////////////////////////////////////////////////////////////
351 ++ (void)sessionRegister:(NSString *)authToken
352 + successBlock:(void (^)(void))success
353 + failureBlock:(void (^)(void))failure
354 +{
355 + if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_USER_SESSION_ENABLED)) {
356 + return;
357 + }
358 +
359 + if (authToken.length == 0) {
360 + if (failure) {
361 + WLLOG(@"Auth token cannot be nil or empty string.");
362 + failure();
363 + }
364 + return;
365 + }
366 +
367 + NSDictionary *userSessionDict = [NSDictionary dictionaryWithObjectsAndKeys:[NSDictionary dictionaryWithObject:authToken forKey:@"auth_token"], @"register", nil];
368 + NSDictionary *postDictionary = @{@"user_session": userSessionDict};
369 +
370 + NSError *error;
371 + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDictionary options:0 error:&error];
372 +
373 + if (error != nil) {
374 + WLLOG(@"Invalid auth token");
375 + if (failure) {
376 + failure();
377 + }
378 + return;
379 + }
380 +
381 + [[Warply sharedService] sendContext:jsonData successBlock:^(NSDictionary *responseDict){
382 + if (success)
383 + success();
384 + } failureBlock:^(NSError *error) {
385 + if (failure)
386 + failure();
387 + }];
388 +}
389 +
390 +#pragma mark - Push Notifications Participation
391 +///////////////////////////////////////////////////////////////////////////////
392 ++ (void)setWarplyNotificationsEnabled:(BOOL)enable successBlock:(void (^)(void))success failureBlock:(void (^)(NSError *error))failure
393 +{
394 + NSDictionary *postDictionary = @{WL_APPLICATION_DATA:@{WL_WARP_NOTIFICATIONS_ENABLED:[NSNumber numberWithBool:enable]}};
395 + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDictionary options:0 error:NULL];
396 +
397 + [[Warply sharedService] sendContext:jsonData successBlock:^(NSDictionary *contextResponse) {
398 + if (success) {
399 + success();
400 + }
401 + } failureBlock:^(NSError *error) {
402 + if (failure) {
403 + failure(error);
404 + }
405 + }];
406 +}
407 +
408 +///////////////////////////////////////////////////////////////////////////////
409 ++ (void)warplyNotificationsEnabledWithsuccessBlock:(void (^)(BOOL isEnabled))success failureBlock:(void (^)(NSError *error))failure;
410 +{
411 + [[Warply sharedService] getContextWithPath:WL_DEVICE_STATUS successBlock:^(id contextResponse) {
412 + BOOL isEnabled = [[contextResponse valueForKey:WL_WARP_NOTIFICATIONS_ENABLED] boolValue];
413 + if (success) {
414 + success(isEnabled);
415 + }
416 + } failureBlock:^(NSError *error) {
417 + if (failure) {
418 + failure(error);
419 + }
420 + }];
421 + return;
422 +}
423 +
424 +@end
1 +/*
2 + Copyright 2010-2016 Warply Inc. All rights reserved.
3 +
4 + Redistribution and use in source and binary forms, without modification,
5 + are permitted provided that the following conditions are met:
6 +
7 + 1. Redistributions of source code must retain the above copyright notice, this
8 + list of conditions and the following disclaimer.
9 +
10 + 2. Redistributions in binaryform must reproduce the above copyright notice,
11 + this list of conditions and the following disclaimer in the documentation
12 + and/or other materials provided with the distribution.
13 +
14 + THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 + EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 + */
25 +
26 +/*!
27 + @header WLCustomNativeAdTableViewCell
28 + The custom table view cell that user may use for presenting native advertisments.
29 + @copyright Warply Inc.
30 + */
31 +
32 +#import <UIKit/UIKit.h>
33 +
34 +@class WLInboxItem;
35 +
36 +/*!
37 + @class WLCustomNativeAdTableViewCell
38 + @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.
39 + */
40 +@interface WLCustomNativeAdTableViewCell : UITableViewCell
41 +
42 +@property (strong, nonatomic) WLInboxItem *item;
43 +
44 +/*!
45 + * @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.
46 + * @param item The WLInboxItem that contains all the data of the campaign to be presented.
47 + */
48 +-(void)setupCustomCell:(WLInboxItem *)item;
49 +
50 +
51 +-(WLInboxItem *)getInboxItem;
52 +
53 +
54 +
55 +@end
1 +//
2 +// WLCustomNativeAdTableViewCell.m
3 +// DemoApp
4 +//
5 +// Created by Nick Xirotyris on 4/2/16.
6 +// Copyright © 2016 YC. All rights reserved.
7 +//
8 +
9 +#import "WLCustomNativeAdTableViewCell.h"
10 +#import "WLInboxItem.h"
11 +
12 +@implementation WLCustomNativeAdTableViewCell
13 +
14 +- (void)awakeFromNib {
15 + [super awakeFromNib];
16 + // Initialization code
17 +}
18 +
19 +-(void)setupCustomCell:(WLInboxItem *)item {
20 + NSLog(@"Custom native TableView Cell setup method.");
21 + self.item = item;
22 +}
23 +
24 +- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
25 + [super setSelected:selected animated:animated];
26 +
27 + // Configure the view for the selected state
28 +}
29 +
30 +-(WLInboxItem *)getInboxItem{
31 + return self.item;
32 +}
33 +
34 +@end
1 +/*
2 + Copyright 2010-2016 Warply Inc. All rights reserved.
3 +
4 + Redistribution and use in source and binary forms, without modification,
5 + are permitted provided that the following conditions are met:
6 +
7 + 1. Redistributions of source code must retain the above copyright notice, this
8 + list of conditions and the following disclaimer.
9 +
10 + 2. Redistributions in binaryform must reproduce the above copyright notice,
11 + this list of conditions and the following disclaimer in the documentation
12 + and/or other materials provided with the distribution.
13 +
14 + THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 + EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 + */
25 +
26 +/*!
27 + @header WLCustomNativeCollectionViewCell
28 + The custom collection view cell that user may use for presenting native advertisments.
29 + @copyright Warply Inc.
30 + */
31 +
32 +#import <UIKit/UIKit.h>
33 +
34 +@class WLInboxItem;
35 +
36 +/*!
37 + @class WLCustomNativeCollectionViewCell
38 + @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.
39 + */
40 +@interface WLCustomNativeCollectionViewCell : UICollectionViewCell
41 +
42 +@property (strong, nonatomic) WLInboxItem *item;
43 +
44 +/*!
45 + * @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.
46 + * @param item The WLInboxItem that contains all the data of the campaign to be presented.
47 + */
48 +-(void)setupCustomCell:(WLInboxItem *)item;
49 +
50 +
51 +-(WLInboxItem *)getInboxItem;
52 +
53 +@end
1 +//
2 +// WLCustomNativeCollectionViewCell.m
3 +// DemoApp
4 +//
5 +// Created by Nick Xirotyris on 4/2/16.
6 +// Copyright © 2016 YC. All rights reserved.
7 +//
8 +
9 +#import "WLCustomNativeCollectionViewCell.h"
10 +#import "WLInboxItem.h"
11 +
12 +@implementation WLCustomNativeCollectionViewCell
13 +
14 +-(void)setupCustomCell:(WLInboxItem *)item {
15 + NSLog(@"Custom native TableView Cell setup method.");
16 + self.item = item;
17 +}
18 +
19 +-(WLInboxItem *)getInboxItem{
20 + return self.item;
21 +}
22 +
23 +@end
1 +/*
2 + Copyright 2010-2016 Warply Inc. All rights reserved.
3 +
4 + Redistribution and use in source and binary forms, without modification,
5 + are permitted provided that the following conditions are met:
6 +
7 + 1. Redistributions of source code must retain the above copyright notice, this
8 + list of conditions and the following disclaimer.
9 +
10 + 2. Redistributions in binaryform must reproduce the above copyright notice,
11 + this list of conditions and the following disclaimer in the documentation
12 + and/or other materials provided with the distribution.
13 +
14 + THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 + EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 + */
25 +
26 +/*!
27 + @header WLNativeAdCollectionViewCell
28 + The CollectionView Cell for native ads.
29 + @copyright Warply Inc.
30 + */
31 +
32 +#import <UIKit/UIKit.h>
33 +#import <WebKit/WebKit.h>
34 +
35 +/*!
36 + @class WLNativeAdCollectionViewCell
37 + @discussion This class contains the properties of the cell of the native ad and the method to setup the cell.
38 + */
39 +@interface WLNativeAdCollectionViewCell : UICollectionViewCell <UIWebViewDelegate>
40 +
41 +/*!
42 + * @property webView
43 + * @abstract The webview that will show the native ad campaign.
44 + */
45 +@property (weak, nonatomic) IBOutlet WKWebView *webView;
46 +/*!
47 + * @property activityIndicator
48 + * @abstract The indicator waiting for the campaign to load.
49 + */
50 +@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *activityIndicator;
51 +
52 +/*!
53 + @methodgroup Setup the cells
54 + */
55 +/*!
56 + * @abstract Shows the content of the native ad campaign.
57 + * @discussion This method setups directly the content of the native ad campaign in the cell when the WLInboxItem is of display_type = feed.
58 + * @param url The url of the campign to be presented.
59 + */
60 +-(void)loadContentwithURL:(NSString *)url;
61 +
62 +@end
1 +//
2 +// WLNativeAdCollectionViewCell.m
3 +// DemoApp
4 +//
5 +// Created by Nick Xirotyris on 19/10/15.
6 +// Copyright © 2015 YC. All rights reserved.
7 +//
8 +
9 +#import "WLNativeAdCollectionViewCell.h"
10 +#import "Warply.h"
11 +
12 +//#import "WLGlobals.h"
13 +
14 +@implementation WLNativeAdCollectionViewCell
15 +
16 +- (id)initWithFrame:(CGRect)frame
17 +{
18 + self = [super initWithFrame:frame];
19 + if (self) {
20 +
21 + // Initialization code
22 + NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:@"WLNativeAdCollectionViewCell" owner:self options:nil];
23 +
24 + if ([arrayOfViews count] < 1) {
25 + return nil;
26 + }
27 +
28 + if (![[arrayOfViews objectAtIndex:0] isKindOfClass:[UICollectionViewCell class]]) {
29 + return nil;
30 + }
31 +
32 + self = [arrayOfViews objectAtIndex:0];
33 +
34 + }
35 +
36 + return self;
37 +
38 +}
39 +
40 +
41 +-(void)loadContentwithURL:(NSString *)url {
42 + NSMutableURLRequest * request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
43 + request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
44 + [request setValue:[Warply sharedService].webId forHTTPHeaderField:@"loyalty-web-id"];
45 + [request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
46 + [request setValue:@"gzip" forHTTPHeaderField:@"User-Agent"];
47 + [self.webView loadRequest:request];
48 + [self.activityIndicator startAnimating];
49 +}
50 +
51 +
52 +-(BOOL)webView:(WKWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
53 +
54 + if (![request.URL.host isEqualToString:WARP_HOST] && ![request.URL.host isEqualToString:@"warplydata.blob.core.windows.net"]) {
55 + [[UIApplication sharedApplication] openURL:request.URL];
56 + }
57 +
58 + return YES;
59 +}
60 +
61 +
62 +-(void)webViewDidFinishLoad:(WKWebView *)webView {
63 + [self.activityIndicator stopAnimating];
64 +}
65 +
66 +-(void)webView:(WKWebView *)webView didFailLoadWithError:(NSError *)error {
67 + NSLog(@"%@", error);
68 + [self.activityIndicator stopAnimating];
69 +}
70 +
71 +@end
1 +<?xml version="1.0" encoding="UTF-8" standalone="no"?>
2 +<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="9531" systemVersion="15D21" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES">
3 + <dependencies>
4 + <deployment identifier="iOS"/>
5 + <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="9529"/>
6 + </dependencies>
7 + <objects>
8 + <placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
9 + <placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
10 + <collectionViewCell opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" reuseIdentifier="adItem" id="9Rt-2X-RuJ" customClass="WLNativeAdCollectionViewCell">
11 + <rect key="frame" x="0.0" y="0.0" width="200" height="150"/>
12 + <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
13 + <view key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center">
14 + <rect key="frame" x="0.0" y="0.0" width="200" height="150"/>
15 + <autoresizingMask key="autoresizingMask"/>
16 + <subviews>
17 + <webView contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="lL4-lm-ZmW">
18 + <rect key="frame" x="0.0" y="0.0" width="200" height="150"/>
19 + <color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
20 + <connections>
21 + <outlet property="delegate" destination="9Rt-2X-RuJ" id="Uuz-NA-aUA"/>
22 + </connections>
23 + </webView>
24 + <activityIndicatorView hidden="YES" opaque="NO" contentMode="scaleToFill" horizontalHuggingPriority="750" verticalHuggingPriority="750" fixedFrame="YES" hidesWhenStopped="YES" style="gray" translatesAutoresizingMaskIntoConstraints="NO" id="Nce-1c-FOV">
25 + <rect key="frame" x="90" y="65" width="20" height="20"/>
26 + </activityIndicatorView>
27 + </subviews>
28 + <color key="backgroundColor" white="0.0" alpha="0.0" colorSpace="calibratedWhite"/>
29 + </view>
30 + <constraints>
31 + <constraint firstItem="lL4-lm-ZmW" firstAttribute="leading" secondItem="9Rt-2X-RuJ" secondAttribute="leading" id="FW4-bb-qnx"/>
32 + <constraint firstAttribute="bottom" secondItem="lL4-lm-ZmW" secondAttribute="bottom" id="PZx-BK-Wud"/>
33 + <constraint firstItem="lL4-lm-ZmW" firstAttribute="top" secondItem="9Rt-2X-RuJ" secondAttribute="top" id="Uw3-Vz-gUN"/>
34 + <constraint firstAttribute="trailing" secondItem="lL4-lm-ZmW" secondAttribute="trailing" id="bb8-0l-EBV"/>
35 + </constraints>
36 + <size key="customSize" width="50" height="205"/>
37 + <connections>
38 + <outlet property="activityIndicator" destination="Nce-1c-FOV" id="JRg-6f-bVF"/>
39 + <outlet property="webView" destination="lL4-lm-ZmW" id="yFg-tC-eyH"/>
40 + </connections>
41 + <point key="canvasLocation" x="186" y="127"/>
42 + </collectionViewCell>
43 + </objects>
44 +</document>
1 +/*
2 + Copyright 2010-2016 Warply Inc. All rights reserved.
3 +
4 + Redistribution and use in source and binary forms, without modification,
5 + are permitted provided that the following conditions are met:
6 +
7 + 1. Redistributions of source code must retain the above copyright notice, this
8 + list of conditions and the following disclaimer.
9 +
10 + 2. Redistributions in binaryform must reproduce the above copyright notice,
11 + this list of conditions and the following disclaimer in the documentation
12 + and/or other materials provided with the distribution.
13 +
14 + THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 + EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 + */
25 +
26 +/*!
27 + @header WLNativeAdTableViewCell
28 + The TableView Cell for native ads.
29 + @copyright Warply Inc.
30 + */
31 +
32 +#import <UIKit/UIKit.h>
33 +#import <WebKit/WebKit.h>
34 +#import "WLInboxItem.h"
35 +/*!
36 + @class WLNativeAdTableViewCell
37 + @discussion This class contains the properties of the cell of the native ad and methods to setup the cell.
38 + */
39 +@interface WLNativeAdTableViewCell : UITableViewCell <UIWebViewDelegate>
40 +
41 +@property (strong, nonatomic) WLInboxItem *item;
42 +
43 +/*!
44 + * @property webView
45 + * @abstract The webview that will show the native ad campaign.
46 + */
47 +@property (weak, nonatomic) IBOutlet WKWebView *webView;
48 +/*!
49 + * @property activityIndicator
50 + * @abstract The indicator waiting for the campaign to load.
51 + */
52 +@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *activityIndicator;
53 +/*!
54 + * @property adImageView
55 + * @abstract The image of the campaign
56 + */
57 +@property (weak, nonatomic) IBOutlet UIImageView *adImageView;
58 +/*!
59 + * @property adLabel
60 + * @abstract This label contains the title and the subtitle of the campaign.
61 + */
62 +@property (weak, nonatomic) IBOutlet UILabel *adLabel;
63 +
64 +/*!
65 + @methodgroup Setup the cells
66 +*/
67 +/*!
68 + * @abstract Setups the cell with a WLInboxItem.
69 + * @discussion This method setups the cell with a WLInboxItem that is related to the native ad campaign that is presented in this cell
70 + * @param item The WLInboxItem that is of display_type = list.
71 + */
72 +-(void)setupCellWithItem:(WLInboxItem *)item;
73 +/*!
74 + * @abstract Shows the content of the native ad campaign.
75 + * @discussion This method setups directly the content of the native ad campaign in the cell when the WLInboxItem is of display_type = feed.
76 + * @param url The url of the campign to be presented.
77 + */
78 +-(void)loadContentwithURL:(NSString *)url;
79 +
80 +@end
1 +//
2 +// WLNativeAdTableViewCell.m
3 +// DemoApp
4 +//
5 +// Created by Nick Xirotyris on 14/10/15.
6 +// Copyright © 2015 YC. All rights reserved.
7 +//
8 +
9 +#import "WLNativeAdTableViewCell.h"
10 +#import "Warply.h"
11 +#import <WebKit/WebKit.h>
12 +#import "UIImageView+AFNetworking.h"
13 +
14 +//#import "WLGlobals.h"
15 +
16 +@implementation WLNativeAdTableViewCell
17 +
18 +- (void)awakeFromNib {
19 + [super awakeFromNib];
20 + // Initialization code
21 +
22 + self.webView.UIDelegate = self;
23 + self.adImageView.clipsToBounds = YES;
24 +}
25 +
26 +- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
27 + [super setSelected:selected animated:animated];
28 +
29 + // Configure the view for the selected state
30 +}
31 +
32 +
33 +-(void)setupCellWithItem:(WLInboxItem *)item {
34 + self.item = item;
35 + self.adLabel.text = item.title;
36 + self.webView.alpha = 0;
37 +
38 + NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[item getImageURL]]];
39 +
40 + [self.activityIndicator startAnimating];
41 +
42 + [self.adImageView setImageWithURLRequest:request
43 + placeholderImage:nil
44 + success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
45 +
46 + [self.activityIndicator stopAnimating];
47 + self.adImageView.image = image;
48 + }
49 + failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
50 + [self.activityIndicator stopAnimating];
51 + }];
52 +}
53 +
54 +
55 +-(void)loadContentwithURL:(NSString *)url {
56 +
57 + self.adLabel.alpha = 0;
58 + self.adImageView.alpha = 0;
59 +
60 + NSMutableURLRequest * request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
61 + request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
62 + [request setValue:[Warply sharedService].webId forHTTPHeaderField:@"loyalty-web-id"];
63 + [request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
64 + [request setValue:@"gzip" forHTTPHeaderField:@"User-Agent"];
65 + [self.webView loadRequest:request];
66 + [self.activityIndicator startAnimating];
67 +}
68 +
69 +
70 +#pragma mark - WebView Delegate
71 +
72 +
73 +-(BOOL)webView:(WKWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
74 +
75 + if (![request.URL.host isEqualToString:WARP_HOST] && ![request.URL.host isEqualToString:@"warplydata.blob.core.windows.net"]) {
76 + [[UIApplication sharedApplication] openURL:request.URL];
77 + }
78 +
79 + return YES;
80 +}
81 +
82 +
83 +-(void)webViewDidFinishLoad:(WKWebView *)webView {
84 + [self.activityIndicator stopAnimating];
85 +}
86 +
87 +-(void)webView:(WKWebView *)webView didFailLoadWithError:(NSError *)error {
88 + NSLog(@"%@", error);
89 + [self.activityIndicator stopAnimating];
90 +}
91 +
92 +
93 +
94 +
95 +
96 +@end
1 +<?xml version="1.0" encoding="UTF-8" standalone="no"?>
2 +<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="9532" systemVersion="15D21" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES">
3 + <dependencies>
4 + <deployment identifier="iOS"/>
5 + <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="9530"/>
6 + <capability name="Aspect ratio constraints" minToolsVersion="5.1"/>
7 + <capability name="Constraints to layout margins" minToolsVersion="6.0"/>
8 + </dependencies>
9 + <objects>
10 + <placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
11 + <placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
12 + <tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" indentationWidth="10" reuseIdentifier="nativeCell" rowHeight="80" id="TUO-3e-Z0c" customClass="WLNativeAdTableViewCell">
13 + <rect key="frame" x="0.0" y="0.0" width="320" height="80"/>
14 + <autoresizingMask key="autoresizingMask"/>
15 + <tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="TUO-3e-Z0c" id="rFP-el-oLd">
16 + <rect key="frame" x="0.0" y="0.0" width="320" height="79.5"/>
17 + <autoresizingMask key="autoresizingMask"/>
18 + <subviews>
19 + <webView contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="95U-Ni-FSn">
20 + <rect key="frame" x="0.0" y="0.0" width="320" height="79"/>
21 + <color key="backgroundColor" white="0.0" alpha="0.0" colorSpace="calibratedWhite"/>
22 + <connections>
23 + <outlet property="delegate" destination="TUO-3e-Z0c" id="8nn-Mf-VRq"/>
24 + </connections>
25 + </webView>
26 + <imageView userInteractionEnabled="NO" contentMode="scaleAspectFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" translatesAutoresizingMaskIntoConstraints="NO" id="xLm-Bp-71W">
27 + <rect key="frame" x="8" y="8" width="152" height="64"/>
28 + </imageView>
29 + <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">
30 + <rect key="frame" x="233" y="65" width="87" height="14"/>
31 + <constraints>
32 + <constraint firstAttribute="height" constant="14" id="SFz-Ux-2Y8"/>
33 + <constraint firstAttribute="width" constant="87" id="k55-7i-nkq"/>
34 + </constraints>
35 + <fontDescription key="fontDescription" type="system" pointSize="12"/>
36 + <color key="textColor" red="0.0" green="0.0" blue="0.0" alpha="1" colorSpace="calibratedRGB"/>
37 + <nil key="highlightedColor"/>
38 + </label>
39 + <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">
40 + <rect key="frame" x="161" y="8" width="151" height="55"/>
41 + <fontDescription key="fontDescription" type="system" pointSize="15"/>
42 + <color key="textColor" red="0.0" green="0.0" blue="0.0" alpha="1" colorSpace="calibratedRGB"/>
43 + <nil key="highlightedColor"/>
44 + </label>
45 + <activityIndicatorView hidden="YES" opaque="NO" contentMode="scaleToFill" horizontalHuggingPriority="750" verticalHuggingPriority="750" fixedFrame="YES" hidesWhenStopped="YES" style="gray" translatesAutoresizingMaskIntoConstraints="NO" id="2i1-rB-bMz">
46 + <rect key="frame" x="150" y="30" width="20" height="20"/>
47 + </activityIndicatorView>
48 + <view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="a1K-T8-Q5a">
49 + <rect key="frame" x="0.0" y="78" width="320" height="1"/>
50 + <color key="backgroundColor" white="0.66666666666666663" alpha="1" colorSpace="calibratedWhite"/>
51 + <constraints>
52 + <constraint firstAttribute="height" constant="1" id="ahQ-nq-Svc"/>
53 + </constraints>
54 + </view>
55 + </subviews>
56 + <constraints>
57 + <constraint firstAttribute="bottom" secondItem="95U-Ni-FSn" secondAttribute="bottom" constant="1" id="2do-aZ-hiv"/>
58 + <constraint firstAttribute="trailing" secondItem="NSR-sb-7cF" secondAttribute="trailing" constant="8" id="3TW-AH-T85"/>
59 + <constraint firstAttribute="trailing" secondItem="95U-Ni-FSn" secondAttribute="trailing" id="DS0-Pz-ZxO"/>
60 + <constraint firstAttribute="trailing" secondItem="a1K-T8-Q5a" secondAttribute="trailing" id="Gi2-gJ-nmY"/>
61 + <constraint firstItem="95U-Ni-FSn" firstAttribute="top" secondItem="rFP-el-oLd" secondAttribute="top" id="GyZ-hA-4Dl"/>
62 + <constraint firstItem="NSR-sb-7cF" firstAttribute="top" secondItem="rFP-el-oLd" secondAttribute="top" constant="8" id="JR8-fp-s3F"/>
63 + <constraint firstItem="95U-Ni-FSn" firstAttribute="leading" secondItem="rFP-el-oLd" secondAttribute="leading" id="NIf-5g-WS2"/>
64 + <constraint firstAttribute="trailing" secondItem="396-VT-2Ee" secondAttribute="trailing" id="Puz-ao-t5a"/>
65 + <constraint firstAttribute="bottomMargin" secondItem="a1K-T8-Q5a" secondAttribute="bottom" id="QCr-O6-1AG"/>
66 + <constraint firstItem="396-VT-2Ee" firstAttribute="top" secondItem="NSR-sb-7cF" secondAttribute="bottom" constant="2" id="WUG-eo-mFh"/>
67 + <constraint firstAttribute="bottom" secondItem="396-VT-2Ee" secondAttribute="bottom" constant="0.5" id="d4X-1L-xI0"/>
68 + <constraint firstItem="a1K-T8-Q5a" firstAttribute="leading" secondItem="rFP-el-oLd" secondAttribute="leading" id="ixG-zU-9Md"/>
69 + <constraint firstItem="NSR-sb-7cF" firstAttribute="leading" secondItem="xLm-Bp-71W" secondAttribute="trailing" constant="1" id="mVf-Ie-GET"/>
70 + <constraint firstItem="xLm-Bp-71W" firstAttribute="width" secondItem="NSR-sb-7cF" secondAttribute="width" id="sHF-sC-dIe"/>
71 + <constraint firstItem="xLm-Bp-71W" firstAttribute="width" secondItem="rFP-el-oLd" secondAttribute="height" multiplier="2:1" id="sXq-4t-rRt"/>
72 + <constraint firstItem="xLm-Bp-71W" firstAttribute="leading" secondItem="rFP-el-oLd" secondAttribute="leading" constant="8" id="tPi-ou-5x7"/>
73 + <constraint firstAttribute="bottom" secondItem="a1K-T8-Q5a" secondAttribute="bottom" id="tQY-Sv-9zd"/>
74 + <constraint firstItem="xLm-Bp-71W" firstAttribute="top" secondItem="rFP-el-oLd" secondAttribute="top" constant="8" id="yCS-mb-vzW"/>
75 + <constraint firstAttribute="bottom" secondItem="xLm-Bp-71W" secondAttribute="bottom" constant="8" id="yRo-mZ-HKk"/>
76 + </constraints>
77 + <variation key="default">
78 + <mask key="constraints">
79 + <exclude reference="sXq-4t-rRt"/>
80 + <exclude reference="QCr-O6-1AG"/>
81 + </mask>
82 + </variation>
83 + </tableViewCellContentView>
84 + <connections>
85 + <outlet property="activityIndicator" destination="2i1-rB-bMz" id="TzL-ld-iTy"/>
86 + <outlet property="adImageView" destination="xLm-Bp-71W" id="TZ7-9X-2hw"/>
87 + <outlet property="adLabel" destination="NSR-sb-7cF" id="WdI-PV-UhH"/>
88 + <outlet property="webView" destination="95U-Ni-FSn" id="JXN-nw-EjM"/>
89 + </connections>
90 + <point key="canvasLocation" x="684" y="370"/>
91 + </tableViewCell>
92 + </objects>
93 +</document>
1 +/*
2 + Copyright 2010-2016 Warply Inc. All rights reserved.
3 +
4 + Redistribution and use in source and binary forms, without modification,
5 + are permitted provided that the following conditions are met:
6 +
7 + 1. Redistributions of source code must retain the above copyright notice, this
8 + list of conditions and the following disclaimer.
9 +
10 + 2. Redistributions in binaryform must reproduce the above copyright notice,
11 + this list of conditions and the following disclaimer in the documentation
12 + and/or other materials provided with the distribution.
13 +
14 + THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 + EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 + */
25 +
26 +/*!
27 + @header WLNativeAdsCollectionMode
28 + The Collection View mode for integrating native ads in a UICollectionView
29 + @copyright Warply Inc.
30 + */
31 +
32 +
33 +#import <UIKit/UIKit.h>
34 +#import <Foundation/Foundation.h>
35 +#import "WLInboxItem.h"
36 +#import "WLCustomNativeCollectionViewCell.h"
37 +
38 +/*!
39 + @protocol WLNativeAdsCollectionModeDelegate
40 + @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.
41 + */
42 +/*!
43 + @methodgroup Showing native ad content
44 + */
45 +/*!
46 + @abstract Presents the content of the native ad.
47 + @discussion Receives a WLInboxItem which you can present to a WLInboxViewController. Also, you can handle its data in any custom way.
48 + */
49 +@protocol WLNativeAdsCollectionModeDelegate <NSObject>
50 +
51 +@optional
52 +- (void)nativeAdDidSelectWithItem:(WLInboxItem *)item;
53 +
54 +@end
55 +
56 +
57 +/*!
58 + @class WLNativeAdsCollectionMode
59 + @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.
60 + */
61 +@interface WLNativeAdsCollectionMode : NSObject
62 +
63 +@property (nonatomic, assign) id<WLNativeAdsCollectionModeDelegate> delegate;
64 +
65 +/*!
66 + * @methodgroup Initialising the CollectionView mode of native ads
67 + */
68 +/*!
69 + * @abstract Initializes the WLNativeAdsCollectionMode object.
70 + * @discussion This class handles and integrates native ads in an original UICollectionView object.
71 + * @param viewController The View Controller where the original collectionView exists.
72 + * @param collectionView The original collectionView object where we will add the native ads.
73 + * @param startPosition The position where the ads will start to appear in the collectionView. It counts from 0.
74 + * @param frequency The frequency with which the ads will appear in the collectionView.
75 + * @param size The size of the cell the native ad will be presented.
76 + * @param displayType The display type of the campaigns that the user will present as native ads.
77 + */
78 +-(id)initWithViewController:(UIViewController <UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout> *)viewController CollectionView:(UICollectionView *)collectionView withStartPosition:(NSInteger)startPosition Frequency:(NSInteger)frequency CellSize:(CGSize)size andDisplayType:(NSString *)displayType;
79 +
80 +/*!
81 + @methodgroup Setting up a custom cell for native ads
82 + */
83 +/*!
84 + * @abstract Setups a custom cell.
85 + * @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.
86 + * @param cell The cell object that user will use as a native Ad cell
87 + * @param cellIdentifier The cell's identifier
88 + * @param nibName The nib's name in the case the cell is designed with a .xib file and not in Storyboard.
89 + */
90 +-(void)setCustomCellForNativeAd:(WLCustomNativeCollectionViewCell *)cell withIdentifier:(NSString *)cellIdentifier andNibName:(NSString *)nibName;
91 +
92 +
93 +/*!
94 + @methodgroup Handling the native Ads CollectionView
95 + */
96 +/*!
97 + * @abstract Refresh the collectionView datasource and delegate.
98 + * @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.
99 + * @param collectionView The original collectionView object which will change after the update.
100 + */
101 +-(void)refreshAdsForCollectionView:(UICollectionView *)collectionView;
102 +/**
103 + * @abstract Defines if the ads will appear in a repeatable way in the collectionView.
104 + * @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.
105 + * @param repeatable BOOL value that sets if the native ads will repeat themselves in the collectionView.
106 + */
107 +-(void)setRepeatable:(BOOL)repeatable;
108 +//-(NSIndexPath *)getOriginalIndexPath:(NSIndexPath *)indexPath;
109 +
110 +@end
1 +//
2 +// WLNativeAdsCollectionMode.m
3 +// DemoApp
4 +//
5 +// Created by Nick Xirotyris on 19/10/15.
6 +// Copyright © 2015 YC. All rights reserved.
7 +//
8 +
9 +#import "WLNativeAdsCollectionMode.h"
10 +#import "WLNativeAdCollectionViewCell.h"
11 +#import "Warply.h"
12 +
13 +
14 +@interface WLNativeAdsCollectionMode () <UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
15 +
16 +@property (weak, nonatomic) id<UICollectionViewDataSource> originalDatasource;
17 +@property (weak, nonatomic) id<UICollectionViewDelegate> originalDelegate;
18 +@property (strong, nonatomic) id<UICollectionViewDelegateFlowLayout> originalFlowLayout;
19 +@property (weak, nonatomic) UICollectionView *nativeCollectionView;
20 +@property (nonatomic, weak) WLCustomNativeCollectionViewCell *customCell;
21 +@property (nonatomic, strong) NSString *customCellIdentifier;
22 +@property (nonatomic, strong) NSString *customCellNibName;
23 +
24 +@property (weak, nonatomic) UIViewController <UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout> *originalVC;
25 +
26 +
27 +@end
28 +
29 +
30 +@implementation WLNativeAdsCollectionMode {
31 + NSInteger adsForCollectionView;
32 + NSInteger startAd;
33 + NSInteger frequencyAd;
34 + NSInteger originalNumberOfsections;
35 + NSInteger currentRows;
36 + NSInteger totalExtraRows;
37 + NSMutableArray *indexArrayOfAds;
38 + NSArray *offersArray;
39 + CGSize cellSize;
40 + NSString *display_type;
41 + BOOL repeatableAds;
42 +}
43 +
44 +
45 +-(id)initWithViewController:(UIViewController<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout> *)viewController CollectionView:(UICollectionView *)collectionView withStartPosition:(NSInteger)startPosition Frequency:(NSInteger)frequency CellSize:(CGSize)size andDisplayType:(NSString *)displayType{
46 +
47 + self = [super init];
48 + if (self) {
49 +
50 + [self getInbox];
51 + [self.nativeCollectionView registerClass:[WLNativeAdCollectionViewCell class] forCellWithReuseIdentifier:@"adItem"];
52 + [collectionView registerClass:[WLNativeAdCollectionViewCell class] forCellWithReuseIdentifier:@"adItem"];
53 +
54 +
55 + self.originalDatasource = collectionView.dataSource;
56 + self.originalDelegate = collectionView.delegate;
57 + self.nativeCollectionView = collectionView;
58 + self.originalVC = viewController;
59 + self.originalFlowLayout = (id<UICollectionViewDelegateFlowLayout>)self.originalDelegate;
60 + startAd = startPosition;
61 + frequencyAd = frequency;
62 + display_type = displayType;
63 +
64 + if ([self.originalDatasource respondsToSelector:@selector(numberOfSectionsInCollectionView:)]) {
65 + originalNumberOfsections = [self.originalDatasource numberOfSectionsInCollectionView:collectionView];
66 + } else {
67 + originalNumberOfsections = 1;
68 + }
69 +
70 + repeatableAds = NO;
71 + currentRows = 0;
72 + totalExtraRows = 0;
73 + cellSize = size;
74 +
75 + }
76 +
77 + return self;
78 +}
79 +
80 +
81 +- (void)refreshAdsForCollectionView:(UICollectionView *)collectionView {
82 + self.originalDatasource = nil;
83 + self.originalDelegate = nil;
84 + self.nativeCollectionView = nil;
85 + collectionView.dataSource = nil;
86 + collectionView.delegate = nil;
87 + collectionView.dataSource = self.originalVC;
88 + collectionView.delegate = self.originalVC;
89 +
90 + self.originalDatasource = collectionView.dataSource;
91 + self.originalDelegate = collectionView.delegate;
92 + self.nativeCollectionView = collectionView;
93 +
94 + if ([self.originalDatasource respondsToSelector:@selector(numberOfSectionsInCollectionView:)]) {
95 + originalNumberOfsections = [self.originalDatasource numberOfSectionsInCollectionView:collectionView];
96 + } else {
97 + originalNumberOfsections = 1;
98 + }
99 +
100 + currentRows = 0;
101 + totalExtraRows = 0;
102 +
103 + [self getInbox];
104 +}
105 +
106 +
107 +-(void)setRepeatable:(BOOL)repeatable {
108 +
109 + repeatableAds = repeatable;
110 +
111 + if (!repeatable) {
112 + int counter = 0;
113 +
114 + for (int i = 0; i < originalNumberOfsections; i++) {
115 +
116 + for (int j = 0; j < [[indexArrayOfAds objectAtIndex:i] count]; j++) {
117 + if ([[[indexArrayOfAds objectAtIndex:i] objectAtIndex:j] isEqual:@(YES)]) {
118 + counter++;
119 + if (counter > adsForCollectionView) {
120 + [[indexArrayOfAds objectAtIndex:i] removeObjectAtIndex:j];
121 + }
122 + }
123 +
124 + }
125 + }
126 +
127 + [self.nativeCollectionView reloadData];
128 +
129 + } else {
130 + NSLog(@"Nothing to remove");
131 + }
132 +}
133 +
134 +
135 +-(void)setCustomCellForNativeAd:(WLCustomNativeCollectionViewCell *)cell withIdentifier:(NSString *)cellIdentifier andNibName:(NSString *)nibName {
136 + self.customCell = cell;
137 + self.customCellIdentifier = cellIdentifier;
138 + self.customCellNibName = nibName;
139 +}
140 +
141 +
142 +-(void)getInbox {
143 +
144 +
145 + [[Warply sharedService] getInboxWithSuccessBlock:^(NSArray *list) {
146 +
147 + NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"(display_type == '%@')", display_type]];
148 + offersArray = [list filteredArrayUsingPredicate:predicate];
149 +
150 + if (offersArray.count > 0) {
151 + [self setupNewRowsPerSection];
152 + [self setRepeatable:repeatableAds];
153 + self.nativeCollectionView.dataSource = self;
154 + self.nativeCollectionView.delegate = self;
155 + self.nativeCollectionView.allowsSelection = YES;
156 + [self.nativeCollectionView reloadData];
157 + }
158 + } failureBlock:^(NSError *error) {
159 + //
160 + }];
161 +}
162 +
163 +
164 +#pragma mark - Original IndexPath & Helpers
165 +
166 +
167 +- (void)setupNewRowsPerSection {
168 +
169 + indexArrayOfAds = [NSMutableArray array];
170 + int count = 0;
171 +
172 + for (int i = 0; i < originalNumberOfsections; i++) {
173 + NSMutableArray *newRows = [NSMutableArray array];
174 + NSInteger total = [self totalRowsWithAdsForSection:i];
175 +
176 + for (int j = 0; j < total; j++) {
177 +
178 + if (count == startAd || (count > startAd && (count - startAd)%(frequencyAd + 1) == 0)) {
179 + [newRows addObject:@(YES)];
180 + } else {
181 + [newRows addObject:@(NO)];
182 + }
183 + count++;
184 + }
185 + [indexArrayOfAds addObject:newRows];
186 + }
187 +
188 + NSLog(@"%@", indexArrayOfAds);
189 +}
190 +
191 +
192 +
193 +-(NSInteger)totalRowsWithAdsForSection:(int)section {
194 +
195 + NSInteger originalRows = [self.originalDatasource collectionView:self.nativeCollectionView numberOfItemsInSection:section];
196 + currentRows += originalRows;
197 +
198 + if (currentRows < startAd) {
199 + return originalRows;
200 + } else {
201 +
202 + if (startAd + 1 >= currentRows - originalRows && startAd + 1 <= currentRows) {
203 + NSInteger extraRows = (currentRows - startAd)/frequencyAd + 1;
204 + totalExtraRows += extraRows;
205 + return extraRows + originalRows;
206 + } else {
207 +
208 + NSInteger extraRowsSoFar = (currentRows - startAd)/frequencyAd + 1;
209 + NSInteger extraRowsForSection = extraRowsSoFar - totalExtraRows;
210 + totalExtraRows += extraRowsForSection;
211 +
212 + return originalRows + extraRowsForSection;
213 + }
214 + }
215 +}
216 +
217 +
218 +-(NSIndexPath *)getOriginalIndexPath:(NSIndexPath *)indexPath {
219 + int extraRows = 0;
220 +
221 + for (int i = 0; i < indexPath.row; i++) {
222 + if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:i] isEqual:@(YES)]) {
223 + extraRows++;
224 + }
225 + }
226 +
227 + // NSLog(@"row: %ld", (long)indexPath.row - extraRows);
228 + return [NSIndexPath indexPathForRow:indexPath.row - extraRows inSection:indexPath.section];
229 +}
230 +
231 +
232 +-(int)getIndexOfAd:(NSIndexPath *)indexPath {
233 +
234 + int adsCount = 0;
235 +
236 + for (int i = 0; i < indexPath.section + 1; i++) {
237 +
238 + int rows = 0;
239 +
240 + if (indexPath.section > i) {
241 + rows = (int)[[indexArrayOfAds objectAtIndex:i] count];
242 + } else {
243 + rows = (int)indexPath.row + 1;
244 + }
245 +
246 + for (int j = 0; j < rows; j++) {
247 + if ([[[indexArrayOfAds objectAtIndex:i] objectAtIndex:j] isEqual:@(YES)]) {
248 + adsCount++;
249 + }
250 + }
251 +
252 + }
253 +
254 + if (adsCount == offersArray.count) {
255 + return adsCount-1;
256 + } else {
257 + return adsCount%offersArray.count - 1;
258 + }
259 +
260 +}
261 +
262 +
263 +
264 +#pragma mark - CollectionView Datasource
265 +
266 +
267 +-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
268 + return originalNumberOfsections;
269 +}
270 +
271 +-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
272 + return [[indexArrayOfAds objectAtIndex:section] count];
273 +}
274 +
275 +-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
276 +
277 +
278 + if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
279 +
280 +
281 + if (self.customCell) {
282 +
283 + NSString *customIdentifier = [NSString stringWithFormat:@"%@", self.customCellIdentifier];
284 +
285 + WLCustomNativeCollectionViewCell *customCell = (WLCustomNativeCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:customIdentifier forIndexPath:indexPath];
286 +
287 + if (self.customCellNibName) {
288 + if (customCell == nil) {
289 + customCell = [[[NSBundle mainBundle] loadNibNamed:[NSString stringWithFormat:@"%@", self.customCellNibName] owner:self options:nil] objectAtIndex:0];
290 + }
291 + }
292 +
293 + if (offersArray.count > 0) {
294 + WLInboxItem *item = (WLInboxItem *)offersArray[[self getIndexOfAd:indexPath]];
295 + [customCell setupCustomCell:item];
296 + }
297 +
298 + return customCell;
299 +
300 + } else {
301 + WLNativeAdCollectionViewCell *cell = (WLNativeAdCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"adItem" forIndexPath:indexPath];
302 +
303 + if (cell == nil) {
304 + cell = [[[NSBundle mainBundle] loadNibNamed:@"WLNativeAdCollectionViewCell" owner:self options:nil] objectAtIndex:0];
305 + }
306 +
307 + cell.backgroundColor = [UIColor whiteColor];
308 +
309 +
310 + WLInboxItem *item = (WLInboxItem *)offersArray[[self getIndexOfAd:indexPath]];
311 + [cell loadContentwithURL:[item getPageURL]];
312 +
313 + return cell;
314 + }
315 +
316 +
317 + } else {
318 + return [self.originalDatasource collectionView:self.nativeCollectionView cellForItemAtIndexPath:[self getOriginalIndexPath:indexPath]];
319 + }
320 +}
321 +
322 +
323 +
324 +
325 +
326 +#pragma mark - CollectionView Delegate
327 +
328 +
329 +-(BOOL)collectionView:(UICollectionView *)collectionView canPerformAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
330 +
331 +
332 + if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
333 + return NO;
334 + } else {
335 + if ([self.originalDelegate respondsToSelector:@selector(collectionView:canPerformAction:forItemAtIndexPath:withSender:)]) {
336 + return [self.originalDelegate collectionView:self.nativeCollectionView canPerformAction:(SEL)action forItemAtIndexPath:[self getOriginalIndexPath:indexPath] withSender:sender];
337 + }
338 +
339 + return NO;
340 + }
341 +
342 +}
343 +
344 +
345 +-(void)collectionView:(UICollectionView *)collectionView performAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
346 +
347 +
348 + if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
349 + return;
350 + } else {
351 + if ([self.originalDelegate respondsToSelector:@selector(collectionView:performAction:forItemAtIndexPath:withSender:)]) {
352 + [self.originalDelegate collectionView:self.nativeCollectionView performAction:(SEL)action forItemAtIndexPath:[self getOriginalIndexPath:indexPath] withSender:sender];
353 + }
354 + }
355 +}
356 +
357 +
358 +-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
359 +
360 + if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
361 + return;
362 + } else {
363 + if ([self.originalDelegate respondsToSelector:@selector(collectionView:didDeselectItemAtIndexPath:)]) {
364 + return [self.originalDelegate collectionView:self.nativeCollectionView didDeselectItemAtIndexPath:[self getOriginalIndexPath:indexPath]];
365 + }
366 + }
367 +}
368 +
369 +
370 +-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
371 +
372 +
373 + if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
374 +
375 + if (offersArray.count > 0) {
376 +
377 + WLInboxItem *item = (WLInboxItem *)offersArray[[self getIndexOfAd:indexPath]];
378 +
379 + if ([[self delegate] respondsToSelector:@selector(nativeAdDidSelectWithItem:)]) {
380 + [[self delegate] nativeAdDidSelectWithItem:item];
381 + }
382 + }
383 +
384 + } else {
385 + if ([self.originalDelegate respondsToSelector:@selector(collectionView:didSelectItemAtIndexPath:)]) {
386 + [self.originalDelegate collectionView:self.nativeCollectionView didSelectItemAtIndexPath:[self getOriginalIndexPath:indexPath]];
387 + }
388 + }
389 +}
390 +
391 +
392 +
393 +-(void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
394 +
395 +
396 + if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
397 + return;
398 + } else {
399 + if ([self.originalDelegate respondsToSelector:@selector(collectionView:didHighlightItemAtIndexPath:)]) {
400 + return [self.originalDelegate collectionView:self.nativeCollectionView didHighlightItemAtIndexPath:[self getOriginalIndexPath:indexPath]];
401 + }
402 + }
403 +}
404 +
405 +
406 +
407 +
408 +-(void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath {
409 +
410 +
411 + if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
412 + return;
413 + } else {
414 + if ([self.originalDelegate respondsToSelector:@selector(collectionView:didUnhighlightItemAtIndexPath:)]) {
415 + return [self.originalDelegate collectionView:self.nativeCollectionView didUnhighlightItemAtIndexPath:[self getOriginalIndexPath:indexPath]];
416 + }
417 + }
418 +}
419 +
420 +
421 +-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
422 +
423 + //FIXME: wrong conditions
424 +
425 +// if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
426 +// return NO;
427 +// } else {
428 +// if ([self.originalDelegate respondsToSelector:@selector(collectionView:shouldSelectItemAtIndexPath:)]) {
429 +// return [self.originalDelegate collectionView:self.nativeCollectionView shouldSelectItemAtIndexPath:[self getOriginalIndexPath:indexPath]];
430 +// }
431 +// }
432 +
433 + return YES;
434 +}
435 +
436 +
437 +-(BOOL)collectionView:(UICollectionView *)collectionView shouldDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
438 +
439 +
440 +// if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
441 +// return NO;
442 +// } else {
443 +// if ([self.originalDelegate respondsToSelector:@selector(collectionView:shouldDeselectItemAtIndexPath:)]) {
444 +// return [self.originalDelegate collectionView:self.nativeCollectionView shouldDeselectItemAtIndexPath:[self getOriginalIndexPath:indexPath]];
445 +// }
446 +// }
447 +
448 + return YES;
449 +}
450 +
451 +
452 +-(BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
453 +
454 + //FIXME: wrong conditions
455 +
456 +// if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
457 +// return NO;
458 +// } else {
459 +// if ([self.originalDelegate respondsToSelector:@selector(collectionView:shouldHighlightItemAtIndexPath:)]) {
460 +// return [self.originalDelegate collectionView:self.nativeCollectionView shouldHighlightItemAtIndexPath:[self getOriginalIndexPath:indexPath]];
461 +// }
462 +// }
463 +//
464 +// return NO;
465 +
466 + return YES;
467 +}
468 +
469 +
470 +- (BOOL)collectionView:(UICollectionView *)collectionView shouldShowMenuForItemAtIndexPath:(NSIndexPath *)indexPath {
471 +
472 +
473 + if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
474 + return NO;
475 + } else {
476 + if ([self.originalDelegate respondsToSelector:@selector(collectionView:shouldShowMenuForItemAtIndexPath:)]) {
477 + return [self.originalDelegate collectionView:self.nativeCollectionView shouldShowMenuForItemAtIndexPath:[self getOriginalIndexPath:indexPath]];
478 + }
479 + }
480 +
481 + return NO;
482 +}
483 +
484 +
485 +-(void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
486 +
487 +
488 + if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
489 + return;
490 + } else {
491 + if ([self.originalDelegate respondsToSelector:@selector(collectionView:willDisplayCell:forItemAtIndexPath:)]) {
492 + return [self.originalDelegate collectionView:self.nativeCollectionView willDisplayCell:cell forItemAtIndexPath:[self getOriginalIndexPath:indexPath]];
493 + }
494 + }
495 +}
496 +
497 +-(void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
498 +
499 +
500 + if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
501 + return;
502 + } else {
503 + if ([self.originalDelegate respondsToSelector:@selector(collectionView:didEndDisplayingCell:forItemAtIndexPath:)]) {
504 + return [self.originalDelegate collectionView:self.nativeCollectionView didEndDisplayingCell:cell forItemAtIndexPath:[self getOriginalIndexPath:indexPath]];
505 + }
506 + }
507 +}
508 +
509 +-(void)collectionView:(UICollectionView *)collectionView willDisplaySupplementaryView:(UICollectionReusableView *)view forElementKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath {
510 +
511 +
512 + if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
513 + return;
514 + } else {
515 + if ([self.originalDelegate respondsToSelector:@selector(collectionView:willDisplaySupplementaryView:forElementKind:atIndexPath:)]) {
516 + return [self.originalDelegate collectionView:self.nativeCollectionView willDisplaySupplementaryView:view forElementKind:elementKind atIndexPath:[self getOriginalIndexPath:indexPath]];
517 + }
518 + }
519 +}
520 +
521 +
522 +-(void)collectionView:(UICollectionView *)collectionView didEndDisplayingSupplementaryView:(UICollectionReusableView *)view forElementOfKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath {
523 +
524 + if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
525 + return;
526 + } else {
527 + if ([self.originalDelegate respondsToSelector:@selector(collectionView:didEndDisplayingSupplementaryView:forElementOfKind:atIndexPath:)]) {
528 + return [self.originalDelegate collectionView:self.nativeCollectionView didEndDisplayingSupplementaryView:view forElementOfKind:elementKind atIndexPath:[self getOriginalIndexPath:indexPath]];
529 + }
530 + }
531 +}
532 +
533 +
534 +
535 +
536 +
537 +#pragma mark - CollectionView Flow Layout
538 +
539 +-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
540 + if ([self.originalFlowLayout respondsToSelector:@selector(collectionView:layout:insetForSectionAtIndex:)]) {
541 + return [self.originalFlowLayout collectionView:self.nativeCollectionView layout:collectionViewLayout insetForSectionAtIndex:section];
542 + }
543 + return UIEdgeInsetsZero;
544 +}
545 +
546 +
547 +
548 +-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
549 + if ([self.originalFlowLayout respondsToSelector:@selector(collectionView:layout:minimumInteritemSpacingForSectionAtIndex:)]) {
550 + return [self.originalFlowLayout collectionView:self.nativeCollectionView layout:collectionViewLayout minimumInteritemSpacingForSectionAtIndex:section];
551 + }
552 + return 10;
553 +}
554 +
555 +
556 +-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
557 + if ([self.originalFlowLayout respondsToSelector:@selector(collectionView:layout:minimumLineSpacingForSectionAtIndex:)]) {
558 + return [self.originalFlowLayout collectionView:self.nativeCollectionView layout:collectionViewLayout minimumLineSpacingForSectionAtIndex:section];
559 + }
560 + return 10;
561 +}
562 +
563 +
564 +-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
565 + if ([self.originalFlowLayout respondsToSelector:@selector(collectionView:layout:referenceSizeForFooterInSection:)]) {
566 + return [self.originalFlowLayout collectionView:self.nativeCollectionView layout:collectionViewLayout referenceSizeForFooterInSection:section];
567 + }
568 + return CGSizeZero;
569 +}
570 +
571 +
572 +-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
573 + if ([self.originalFlowLayout respondsToSelector:@selector(collectionView:layout:referenceSizeForHeaderInSection:)]) {
574 + return [self.originalFlowLayout collectionView:self.nativeCollectionView layout:collectionViewLayout referenceSizeForHeaderInSection:section];
575 + }
576 + return CGSizeZero;
577 +}
578 +
579 +
580 +-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
581 + if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
582 + return cellSize;
583 + } else {
584 + if ([self.originalDelegate respondsToSelector:@selector(collectionView:layout:sizeForItemAtIndexPath:)]) {
585 + return [self.originalFlowLayout collectionView:self.nativeCollectionView layout:collectionViewLayout sizeForItemAtIndexPath:[self getOriginalIndexPath:indexPath]];
586 + }
587 + }
588 +
589 + UICollectionViewFlowLayout *flow = (UICollectionViewFlowLayout *)collectionView.collectionViewLayout;
590 +
591 + return flow.itemSize;
592 +}
593 +
594 +@end
1 +/*
2 + Copyright 2010-2016 Warply Inc. All rights reserved.
3 +
4 + Redistribution and use in source and binary forms, without modification,
5 + are permitted provided that the following conditions are met:
6 +
7 + 1. Redistributions of source code must retain the above copyright notice, this
8 + list of conditions and the following disclaimer.
9 +
10 + 2. Redistributions in binaryform must reproduce the above copyright notice,
11 + this list of conditions and the following disclaimer in the documentation
12 + and/or other materials provided with the distribution.
13 +
14 + THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 + EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 + */
25 +
26 +/*!
27 + @header WLNativeAdsTableMode
28 + The Table View mode for integrating native ads in a UITableView
29 + @copyright Warply Inc.
30 + */
31 +
32 +
33 +
34 +#import <UIKit/UIKit.h>
35 +#import <Foundation/Foundation.h>
36 +#import "WLInboxItem.h"
37 +#import "WLCustomNativeAdTableViewCell.h"
38 +
39 +
40 +/*!
41 + @protocol WLNativeAdsTableModeDelegate
42 + @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.
43 + */
44 +/*!
45 + @methodgroup Showing native ad content
46 + */
47 +/*!
48 + @abstract Presents the content of the native ad.
49 + @discussion Receives a WLInboxItem which you can present to a WLInboxViewController. Also, you can handle its data in any custom way.
50 + */
51 +@protocol WLNativeAdsTableModeDelegate <NSObject>
52 +
53 +@optional
54 +- (void)nativeAdDidSelectWithItem:(WLInboxItem *)item;
55 +
56 +@end
57 +
58 +
59 +/*!
60 + @class WLNativeAdsTableMode
61 + @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
62 + */
63 +@interface WLNativeAdsTableMode : NSObject <UITableViewDataSource, UITableViewDelegate>
64 +
65 +@property (nonatomic, assign) id<WLNativeAdsTableModeDelegate> delegate;
66 +
67 +
68 +/*!
69 + @methodgroup Initialising the TableView mode of native ads
70 + */
71 +/*!
72 + @abstract Initializes the WLNativeAdsTableMode object.
73 + @discussion This class handles and integrates native ads in an original UITableView object.
74 + @param viewController The View Controller where the original tableview exists.
75 + @param tableView The original tableview object where we will add the native ads.
76 + @param startPosition The position where the ads will start to appear in the tableView. It counts from 0.
77 + @param frequency The frequency with which the ads will appear in the tableView.
78 + @param adHeight The height of the cell the native ad will be presented.
79 + @param displayType The display type of the campaigns that the user will present as native ads.
80 + */
81 +-(id)initWithViewController:(UIViewController <UITableViewDataSource,UITableViewDelegate> *)viewController Tableview:(UITableView *)tableView withStartPosition:(NSInteger)startPosition Frequency:(NSInteger)frequency Height:(CGFloat)adHeight andDisplayType:(NSString *)displayType;
82 +
83 +/*!
84 + @methodgroup Setting up a custom cell for native ads
85 + */
86 +/*!
87 + * @abstract Setups a custom cell.
88 + * @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.
89 + * @param cell The cell object that user will use as a native Ad cell
90 + * @param cellIdentifier The cell's identifier
91 + * @param nibName The nib's name in the case the cell is designed with a .xib file and not in Storyboard.
92 + */
93 +-(void)setCustomCellForNativeAd:(WLCustomNativeAdTableViewCell *)cell withIdentifier:(NSString *)cellIdentifier andNibName:(NSString *)nibName;
94 +
95 +/*!
96 + @methodgroup Handling the native Ads TableView
97 + */
98 +/*!
99 + @abstract Refresh the tableView datasource and delegate.
100 + @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.
101 + @param tableView The original tableview object which will change after the update.
102 + */
103 +-(void)refreshAdsForTableView:(UITableView *)tableView;
104 +/*!
105 + @abstract Defines if the ads will appear in a repeatable way in the tableView.
106 + @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.
107 + @param repeatable BOOL value that sets fi the native ads will repeat themselves in the tableView.
108 + */
109 +-(void)setRepeatable:(BOOL)repeatable;
110 +//-(NSIndexPath *)getOriginalIndexPath:(NSIndexPath *)indexPath;
111 +
112 +@end
1 +//
2 +// WLNativeAds.m
3 +// DemoApp
4 +//
5 +// Created by Nick Xirotyris on 14/10/15.
6 +// Copyright © 2015 YC. All rights reserved.
7 +//
8 +
9 +#import "WLNativeAdsTableMode.h"
10 +#import "Warply.h"
11 +#import <UIKit/UIKit.h>
12 +#import "WLNativeAdTableViewCell.h"
13 +#import <AVFoundation/AVFoundation.h>
14 +
15 +
16 +
17 +@interface WLNativeAdsTableMode ()
18 +
19 +@property (nonatomic, strong) id<UITableViewDelegate> originalDelegate;
20 +@property (nonatomic, weak) id<UITableViewDataSource> originalDataSource;
21 +@property (nonatomic, weak) UITableView *nativeTableView;
22 +@property (nonatomic, weak) WLCustomNativeAdTableViewCell *customCell;
23 +@property (nonatomic, strong) NSString *customCellIdentifier;
24 +@property (nonatomic, strong) NSString *customCellNibName;
25 +
26 +@property(nonatomic, weak) UIViewController <UITableViewDataSource,UITableViewDelegate> *originalVC;
27 +@end
28 +
29 +@implementation WLNativeAdsTableMode {
30 + NSArray *offersArray;
31 + CGFloat nativeAdHeight;
32 + NSInteger startAd;
33 + NSInteger frequencyAd;
34 + NSInteger totalOriginalRows;
35 + NSInteger totalExtraRows;
36 + NSInteger currentRows;
37 + NSInteger originalNumberOfsections;
38 + NSMutableArray *originalRowsPerSection;
39 + NSMutableArray *indexArrayOfAds;
40 + NSString *display_type;
41 +
42 + BOOL repeatableAds;
43 +}
44 +
45 +
46 +
47 +-(id)initWithViewController:(UIViewController <UITableViewDataSource,UITableViewDelegate> *)viewController Tableview:(UITableView *)tableView withStartPosition:(NSInteger)startPosition Frequency:(NSInteger)frequency Height:(CGFloat)adHeight andDisplayType:(NSString *)displayType{
48 + NSLog(@"%@", displayType);
49 + self = [super init];
50 + if (self) {
51 +
52 + [self.nativeTableView registerNib:[UINib nibWithNibName:@"WLNativeAdTableViewCell" bundle:nil] forCellReuseIdentifier:@"nativeCell"];
53 + [tableView registerNib:[UINib nibWithNibName:@"WLNativeAdTableViewCell" bundle:nil] forCellReuseIdentifier:@"nativeCell"];
54 +
55 + self.originalDataSource = tableView.dataSource;
56 + self.originalDelegate = tableView.delegate;
57 + self.nativeTableView = tableView;
58 + self.originalVC = viewController;
59 +
60 + if ([self.originalDataSource respondsToSelector:@selector(numberOfSectionsInTableView:)]) {
61 + originalNumberOfsections = [self.originalDataSource numberOfSectionsInTableView:tableView];
62 + } else {
63 + originalNumberOfsections = 1;
64 + }
65 +
66 + currentRows = 0;
67 + totalExtraRows = 0;
68 + startAd = startPosition;
69 + frequencyAd = frequency;
70 + nativeAdHeight = adHeight;
71 + display_type = displayType;
72 + repeatableAds = NO;
73 +
74 + [self getInbox];
75 +
76 +// tableView.dataSource = self.nativeTableView.dataSource;
77 +// tableView.delegate = self.nativeTableView.delegate;
78 +
79 + }
80 +
81 + return self;
82 +}
83 +
84 +
85 +- (void)refreshAdsForTableView:(UITableView *)tableView {
86 + self.originalDataSource = nil;
87 + self.originalDelegate = nil;
88 + self.nativeTableView = nil;
89 + tableView.dataSource = nil;
90 + tableView.delegate = nil;
91 + tableView.dataSource = self.originalVC;
92 + tableView.delegate = self.originalVC;
93 +
94 + self.originalDataSource = tableView.dataSource;
95 + self.originalDelegate = tableView.delegate;
96 + self.nativeTableView = tableView;
97 +
98 + if ([tableView.dataSource respondsToSelector:@selector(numberOfSectionsInTableView:)]) {
99 + originalNumberOfsections = [tableView.dataSource numberOfSectionsInTableView:tableView];
100 + } else {
101 + originalNumberOfsections = 1;
102 + }
103 +
104 + currentRows = 0;
105 + totalExtraRows = 0;
106 +
107 + [self getInbox];
108 +}
109 +
110 +
111 +-(void)setCustomCellForNativeAd:(WLCustomNativeAdTableViewCell *)cell withIdentifier:(NSString *)cellIdentifier andNibName:(NSString *)nibName {
112 + self.customCell = cell;
113 + self.customCellIdentifier = cellIdentifier;
114 + self.customCellNibName = nibName;
115 +}
116 +
117 +
118 +-(void)setRepeatable:(BOOL)repeatable {
119 +
120 + repeatableAds = repeatable;
121 +
122 + if (!repeatable) {
123 + int counter = 0;
124 +
125 + for (int i = 0; i < originalNumberOfsections; i++) {
126 +
127 + for (int j = 0; j < [[indexArrayOfAds objectAtIndex:i] count]; j++) {
128 + if ([[[indexArrayOfAds objectAtIndex:i] objectAtIndex:j] isEqual:@(YES)]) {
129 + counter++;
130 + if (counter > offersArray.count) {
131 + [[indexArrayOfAds objectAtIndex:i] removeObjectAtIndex:j];
132 + }
133 + }
134 +
135 + }
136 + }
137 +
138 + [self.nativeTableView reloadData];
139 +
140 + } else {
141 + NSLog(@"Nothing to remove");
142 + }
143 +}
144 +
145 +
146 +-(void)getInbox {
147 +
148 + [[Warply sharedService] getInboxWithSuccessBlock:^(NSArray *list) {
149 +
150 + NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"(display_type == '%@')", display_type]];
151 + offersArray = [list filteredArrayUsingPredicate:predicate];
152 +
153 + if (offersArray.count > 0) {
154 + [self setupNewRowsPerSection];
155 + [self setRepeatable:repeatableAds];
156 + self.nativeTableView.dataSource = self;
157 + self.nativeTableView.delegate = self;
158 +
159 + [self.nativeTableView reloadData];
160 + }
161 +
162 + } failureBlock:^(NSError *error) {
163 + //
164 + }];
165 +}
166 +
167 +
168 +#pragma mark - Original IndexPath & Helpers
169 +
170 +-(NSIndexPath *)getOriginalIndexPath:(NSIndexPath *)indexPath {
171 + int extraRows = 0;
172 +
173 + for (int i = 0; i < indexPath.row; i++) {
174 + if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:i] isEqual:@(YES)]) {
175 + extraRows++;
176 + }
177 + }
178 +
179 + return [NSIndexPath indexPathForRow:indexPath.row - extraRows inSection:indexPath.section];
180 +}
181 +
182 +
183 +
184 +- (void)setupNewRowsPerSection {
185 +
186 + indexArrayOfAds = [NSMutableArray array];
187 + int count = 0;
188 +
189 + for (int i = 0; i < originalNumberOfsections; i++) {
190 + NSMutableArray *newRows = [NSMutableArray array];
191 + NSInteger total = [self totalRowsWithAdsForSection:i];
192 +
193 + for (int j = 0; j < total; j++) {
194 +
195 + if (count == startAd || (count > startAd && (count - startAd)%(frequencyAd + 1) == 0)) {
196 + [newRows addObject:@(YES)];
197 + } else {
198 + [newRows addObject:@(NO)];
199 + }
200 + count++;
201 + }
202 + [indexArrayOfAds addObject:newRows];
203 + }
204 +
205 +}
206 +
207 +
208 +
209 +
210 +-(NSInteger)totalRowsWithAdsForSection:(int)section {
211 +
212 + NSInteger originalRows = [self.originalDataSource tableView:self.nativeTableView numberOfRowsInSection:section];
213 + currentRows += originalRows;
214 +
215 + if (currentRows < startAd) {
216 + return originalRows;
217 + } else {
218 +
219 + if (startAd + 1 >= currentRows - originalRows && startAd + 1 <= currentRows) {
220 + NSInteger extraRows = (currentRows - startAd)/frequencyAd + 1;
221 + totalExtraRows += extraRows;
222 + return extraRows + originalRows;
223 + } else {
224 +
225 + NSInteger extraRowsSoFar = (currentRows - startAd)/frequencyAd + 1;
226 + NSInteger extraRowsForSection = extraRowsSoFar - totalExtraRows;
227 + totalExtraRows += extraRowsForSection;
228 +
229 + return originalRows + extraRowsForSection;
230 + }
231 + }
232 +}
233 +
234 +
235 +-(int)getIndexOfAd:(NSIndexPath *)indexPath {
236 +
237 + int adsCount = 0;
238 +
239 + for (int i = 0; i < indexPath.section + 1; i++) {
240 +
241 + int rows = 0;
242 +
243 + if (indexPath.section > i) {
244 + rows = (int)[[indexArrayOfAds objectAtIndex:i] count];
245 + } else {
246 + rows = (int)indexPath.row + 1;
247 + }
248 +
249 + for (int j = 0; j < rows; j++) {
250 + if ([[[indexArrayOfAds objectAtIndex:i] objectAtIndex:j] isEqual:@(YES)]) {
251 + adsCount++;
252 + }
253 + }
254 +
255 + }
256 +
257 + if (adsCount == offersArray.count) {
258 + return adsCount-1;
259 + } else {
260 + return adsCount%offersArray.count - 1;
261 + }
262 +
263 +
264 +}
265 +
266 +
267 +
268 +#pragma mark - TableView Datasource
269 +
270 +
271 +-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
272 + return originalNumberOfsections;
273 +}
274 +
275 +
276 +-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
277 + return [[indexArrayOfAds objectAtIndex:section] count];
278 +}
279 +
280 +
281 +
282 +-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
283 +
284 + if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
285 +
286 + if (self.customCell) {
287 +
288 + NSString *customIdentifier = [NSString stringWithFormat:@"%@", self.customCellIdentifier];
289 +
290 + WLCustomNativeAdTableViewCell *customCell = (WLCustomNativeAdTableViewCell *)[tableView dequeueReusableCellWithIdentifier:customIdentifier];
291 +
292 + if (self.customCellNibName) {
293 + if (customCell == nil) {
294 + customCell = [[[NSBundle mainBundle] loadNibNamed:[NSString stringWithFormat:@"%@", self.customCellNibName] owner:self options:nil] objectAtIndex:0];
295 + }
296 + }
297 +
298 + if (offersArray.count > 0) {
299 + WLInboxItem *item = (WLInboxItem *)offersArray[[self getIndexOfAd:indexPath]];
300 + [customCell setupCustomCell:item];
301 + }
302 + [WLAnalyticsManager logEventWithEventId:[NSString stringWithFormat:@"native_campaign_view:%@",customCell.item.session_uuid] pageId:@"" actionMetadata:nil];
303 + NSLog(@"LOG EVENT with Event ID : %@", [NSString stringWithFormat:@"native_campaign_view:%@", customCell.item.session_uuid]);
304 +
305 + return customCell;
306 +
307 + } else {
308 +
309 + WLNativeAdTableViewCell *cell = (WLNativeAdTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"nativeCell"];
310 +
311 + if (cell == nil) {
312 + cell = [[[NSBundle mainBundle] loadNibNamed:@"WLNativeAdTableViewCell" owner:self options:nil] objectAtIndex:0];
313 + }
314 +
315 + cell.selectionStyle = UITableViewCellSelectionStyleNone;
316 +
317 + if (offersArray.count > 0) {
318 +
319 + WLInboxItem *item = (WLInboxItem *)offersArray[[self getIndexOfAd:indexPath]];
320 +
321 + if ([item.display_type isEqualToString:@"list"]) {
322 + [cell setupCellWithItem:item];
323 + // [cell loadContentwithURL:[item getPageURL]];
324 + } else if ([item.display_type isEqualToString:@"feed"]){
325 + [cell loadContentwithURL:[item getPageURL]];
326 + }
327 + }
328 + [WLAnalyticsManager logEventWithEventId:[NSString stringWithFormat:@"native_campaign_view:%@", cell.item.session_uuid] pageId:@"" actionMetadata:nil];
329 + NSLog(@"LOG EVENT with Event ID : %@", [NSString stringWithFormat:@"native_campaign_view:%@", cell.item.session_uuid]);
330 +
331 + return cell;
332 + }
333 +
334 +
335 + } else {
336 + UITableViewCell *original = [self.originalDataSource tableView:self.nativeTableView cellForRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
337 + original.selectionStyle = UITableViewCellSelectionStyleNone;
338 + return original;
339 + }
340 +
341 +}
342 +
343 +
344 +-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
345 + if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
346 + return NO;
347 + }
348 + else {
349 + if ([self.originalDataSource respondsToSelector:@selector(tableView:canEditRowAtIndexPath:)]) {
350 + return [self.originalDataSource tableView:self.nativeTableView canEditRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
351 + }
352 + }
353 + return YES;
354 +}
355 +
356 +-(BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
357 + if ([self.originalDataSource respondsToSelector:@selector(tableView:canMoveRowAtIndexPath:)]) {
358 + return [self.originalDataSource tableView:self.nativeTableView canMoveRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
359 + }
360 + return NO;
361 +}
362 +
363 +
364 +-(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
365 + if ([[[indexArrayOfAds objectAtIndex:sourceIndexPath.section] objectAtIndex:sourceIndexPath.row] isEqual:@(YES)]) {
366 + return;
367 + }
368 + else {
369 + if ([self.originalDataSource respondsToSelector:@selector(tableView:moveRowAtIndexPath:toIndexPath:)]) {
370 + [self.originalDataSource tableView:self.nativeTableView moveRowAtIndexPath:[self getOriginalIndexPath:sourceIndexPath] toIndexPath:[self getOriginalIndexPath:destinationIndexPath]];
371 + }
372 + }
373 +}
374 +
375 +
376 +-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
377 + if ([self.originalDataSource respondsToSelector:@selector(tableView:commitEditingStyle:forRowAtIndexPath:)]) {
378 + [self.originalDataSource tableView:self.nativeTableView commitEditingStyle:editingStyle forRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
379 + }
380 +}
381 +
382 +
383 +-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
384 + if ([self.originalDataSource respondsToSelector:@selector(tableView:titleForHeaderInSection:)]) {
385 + return [self.originalDataSource tableView:self.nativeTableView titleForHeaderInSection:section];
386 + }
387 + return nil;
388 +}
389 +
390 +-(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
391 + if ([self.originalDataSource respondsToSelector:@selector(tableView:titleForFooterInSection:)]) {
392 + return [self.originalDataSource tableView:self.nativeTableView titleForFooterInSection:section];
393 + }
394 + return nil;
395 +}
396 +
397 +
398 +
399 +
400 +#pragma mark - TableView Delegate
401 +
402 +
403 +-(void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
404 + if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
405 +// NSLog(@"Ad accessory button pressed pressed");
406 + }
407 + else {
408 +
409 + if ([self.originalDelegate respondsToSelector:@selector(tableView:accessoryButtonTappedForRowWithIndexPath:)]) {
410 + [self.originalDelegate tableView:self.nativeTableView accessoryButtonTappedForRowWithIndexPath:[self getOriginalIndexPath:indexPath]];
411 + }
412 + }
413 +}
414 +
415 +
416 +
417 +
418 +-(BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
419 + if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
420 + return NO;
421 + }
422 + else {
423 + if ([self.originalDelegate respondsToSelector:@selector(tableView:canPerformAction:forRowAtIndexPath:withSender:)]) {
424 + return [self.originalDelegate tableView:self.nativeTableView canPerformAction:(SEL)action forRowAtIndexPath:[self getOriginalIndexPath:indexPath] withSender:sender];
425 + }
426 + }
427 + return NO;
428 +}
429 +
430 +
431 +
432 +-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
433 + if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
434 + //NSLog(@"Will display Ad cell");
435 + }
436 + else {
437 + if ([self.originalDelegate respondsToSelector:@selector(tableView:willDisplayCell:forRowAtIndexPath:)]) {
438 + [self.originalDelegate tableView:self.nativeTableView willDisplayCell:cell forRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
439 + }
440 + }
441 +}
442 +
443 +- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
444 + if ([self.originalDelegate respondsToSelector:@selector(tableView:didEndDisplayingCell:forRowAtIndexPath:)]) {
445 + [self.originalDelegate tableView:self.nativeTableView didEndDisplayingCell:cell forRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
446 + }
447 +}
448 +
449 +
450 +-(NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
451 + if ([self.originalDelegate respondsToSelector:@selector(tableView:editActionsForRowAtIndexPath:)]) {
452 + return [self.originalDelegate tableView:self.nativeTableView editActionsForRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
453 + }
454 +
455 + return nil;
456 +}
457 +
458 +
459 +-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
460 + if ([self.originalDelegate respondsToSelector:@selector(tableView:editingStyleForRowAtIndexPath:)]) {
461 + return [self.originalDelegate tableView:self.nativeTableView editingStyleForRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
462 + }
463 + return UITableViewCellEditingStyleNone;
464 +}
465 +
466 +
467 +-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
468 + if ([self.originalDelegate respondsToSelector:@selector(tableView:estimatedHeightForRowAtIndexPath:)]) {
469 + return [self.originalDelegate tableView:self.nativeTableView estimatedHeightForRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
470 + }
471 +
472 + return 80;
473 +}
474 +
475 +
476 +
477 +-(NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath {
478 + if ([self.originalDelegate respondsToSelector:@selector(tableView:indentationLevelForRowAtIndexPath:)]) {
479 + return [self.originalDelegate tableView:self.nativeTableView indentationLevelForRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
480 + }
481 +
482 + return 2;
483 +}
484 +
485 +
486 +-(void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
487 + if ([self.originalDelegate respondsToSelector:@selector(tableView:performAction:forRowAtIndexPath:withSender:)]) {
488 + [self.originalDelegate tableView:self.nativeTableView performAction:(SEL)action forRowAtIndexPath:[self getOriginalIndexPath:indexPath] withSender:sender];
489 + }
490 +
491 + return;
492 +}
493 +
494 +
495 +-(BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath {
496 + if ([self.originalDelegate respondsToSelector:@selector(tableView:shouldShowMenuForRowAtIndexPath:)]) {
497 + return [self.originalDelegate tableView:self.nativeTableView shouldShowMenuForRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
498 + }
499 +
500 + return NO;
501 +}
502 +
503 +
504 +
505 +
506 +-(void)tableView:(UITableView *)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath {
507 + if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
508 + // NSLog(@"Will begin editing Ad cell");
509 + }
510 + else {
511 + if ([self.originalDelegate respondsToSelector:@selector(tableView:willBeginEditingRowAtIndexPath:)]) {
512 + [self.originalDelegate tableView:self.nativeTableView willBeginEditingRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
513 + }
514 + }
515 +}
516 +
517 +
518 +-(void)tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
519 + if ([self.originalDelegate respondsToSelector:@selector(tableView:didEndEditingRowAtIndexPath:)]) {
520 + [self.originalDelegate tableView:self.nativeTableView didEndEditingRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
521 + }
522 +}
523 +
524 +
525 +-(void)tableView:(UITableView *)tableView didHighlightRowAtIndexPath:(NSIndexPath *)indexPath {
526 + if ([self.originalDelegate respondsToSelector:@selector(tableView:didHighlightRowAtIndexPath:)]) {
527 + [self.originalDelegate tableView:self.nativeTableView didHighlightRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
528 + }
529 +}
530 +
531 +
532 +-(void)tableView:(UITableView *)tableView didUnhighlightRowAtIndexPath:(NSIndexPath *)indexPath {
533 +
534 + if ([self.originalDelegate respondsToSelector:@selector(tableView:didUnhighlightRowAtIndexPath:)]) {
535 + [self.originalDelegate tableView:self.nativeTableView didUnhighlightRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
536 + }
537 +}
538 +
539 +
540 +
541 +
542 +-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
543 +
544 + if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
545 +
546 + WLInboxItem *item = (WLInboxItem *)offersArray[[self getIndexOfAd:indexPath]];
547 +
548 + if ([item.display_type isEqualToString:@"list"]) {
549 + return nativeAdHeight;
550 + } else if ([item.display_type isEqualToString:@"feed"]){
551 + return 300;
552 + }
553 +
554 + return nativeAdHeight;
555 + } else {
556 + if ([self.originalDelegate respondsToSelector:@selector(tableView:heightForRowAtIndexPath:)]) {
557 + return [self.originalDelegate tableView:self.nativeTableView heightForRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
558 + }
559 + }
560 +
561 + return tableView.rowHeight;
562 +}
563 +
564 +
565 +
566 +-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
567 + if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
568 + // NSLog(@"Will select ad");
569 + }
570 + else {
571 + if ([self.originalDelegate respondsToSelector:@selector(tableView:willSelectRowAtIndexPath:)]) {
572 + [self.originalDelegate tableView:self.nativeTableView willSelectRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
573 + }
574 + }
575 +
576 + return indexPath;
577 +}
578 +
579 +
580 +-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
581 +
582 +
583 + if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
584 + NSLog(@"Ad pressed");
585 +
586 + if (offersArray.count > 0) {
587 +
588 + WLInboxItem *item = (WLInboxItem *)offersArray[[self getIndexOfAd:indexPath]];
589 +
590 + if ([[self delegate] respondsToSelector:@selector(nativeAdDidSelectWithItem:)]) {
591 + [[self delegate] nativeAdDidSelectWithItem:item];
592 + }
593 +
594 + [WLAnalyticsManager logEventWithEventId:[NSString stringWithFormat:@"native_campaign_click:%@", item.session_uuid] pageId:@"" actionMetadata:nil];
595 + NSLog(@"LOG EVENT with Event ID : %@", [NSString stringWithFormat:@"native_campaign_click:%@", item.session_uuid]);
596 + }
597 +
598 + }
599 + else {
600 + if ([self.originalDelegate respondsToSelector:@selector(tableView:didSelectRowAtIndexPath:)]) {
601 + [self.originalDelegate tableView:self.nativeTableView didSelectRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
602 + }
603 + }
604 +}
605 +
606 +
607 +-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
608 + if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
609 + // NSLog(@"Ad deselected");
610 + }
611 + else {
612 + if ([self.originalDelegate respondsToSelector:@selector(tableView:didDeselectRowAtIndexPath:)]) {
613 + [self.originalDelegate tableView:self.nativeTableView didDeselectRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
614 + }
615 + }
616 +}
617 +
618 +
619 +-(NSIndexPath *)tableView:(UITableView *)tableView willDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
620 + if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
621 + //NSLog(@"Will deselect ad");
622 + }
623 + else {
624 + if ([self.originalDelegate respondsToSelector:@selector(tableView:willDeselectRowAtIndexPath:)]) {
625 + [self.originalDelegate tableView:self.nativeTableView willDeselectRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
626 + }
627 + }
628 +
629 + return indexPath;
630 +}
631 +
632 +
633 +
634 +
635 +-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
636 +
637 + if ([self.originalDelegate respondsToSelector:@selector(tableView:viewForFooterInSection:)]) {
638 + return [self.originalDelegate tableView:self.nativeTableView viewForFooterInSection:section];
639 + }
640 + return [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
641 +}
642 +
643 +
644 +
645 +-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
646 +
647 + if ([self.originalDelegate respondsToSelector:@selector(tableView:viewForHeaderInSection:)]) {
648 + return [self.originalDelegate tableView:self.nativeTableView viewForHeaderInSection:section];
649 + }
650 + return [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
651 +}
652 +
653 +
654 +
655 +-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
656 + if ([self.originalDelegate respondsToSelector:@selector(tableView:heightForHeaderInSection:)]) {
657 + return [self.originalDelegate tableView:self.nativeTableView heightForHeaderInSection:section];
658 + }
659 +
660 + if ([self.originalDelegate respondsToSelector:@selector(tableView:viewForHeaderInSection:)]) {
661 + UIView *header = (UIView *)[self.originalDelegate tableView:self.nativeTableView viewForHeaderInSection:section];
662 + return header.bounds.size.height;
663 + }
664 +
665 +
666 + return 0;
667 +}
668 +
669 +
670 +//-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForHeaderInSection:(NSInteger)section {
671 +// if ([self.originalDelegate respondsToSelector:@selector(tableView:estimatedHeightForHeaderInSection:)]) {
672 +// return [self.originalDelegate tableView:self.nativeTableView estimatedHeightForHeaderInSection:section];
673 +// }
674 +// return 0;
675 +//}
676 +
677 +
678 +
679 +- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
680 + if ([self.originalDelegate respondsToSelector:@selector(tableView:heightForFooterInSection:)]) {
681 + return [self.originalDelegate tableView:self.nativeTableView heightForFooterInSection:section];
682 + }
683 +
684 + if ([self.originalDelegate respondsToSelector:@selector(tableView:viewForFooterInSection:)]) {
685 + UIView *footer = (UIView *)[self.originalDelegate tableView:self.nativeTableView viewForFooterInSection:section];
686 + return footer.bounds.size.height;
687 + }
688 +
689 + return 0;
690 +}
691 +
692 +
693 +//-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForFooterInSection:(NSInteger)section {
694 +// if ([self.originalDelegate respondsToSelector:@selector(tableView:estimatedHeightForFooterInSection:)]) {
695 +// return [self.originalDelegate tableView:self.nativeTableView estimatedHeightForFooterInSection:section];
696 +// }
697 +// return 0;
698 +//}
699 +
700 +
701 +
702 +-(void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
703 +
704 + if ([self.originalDelegate respondsToSelector:@selector(tableView:willDisplayHeaderView:forSection:)]) {
705 + [self.originalDelegate tableView:self.nativeTableView willDisplayHeaderView:view forSection:section];
706 + }
707 +}
708 +
709 +-(void)tableView:(UITableView *)tableView didEndDisplayingHeaderView:(UIView *)view forSection:(NSInteger)section {
710 + if ([self.originalDelegate respondsToSelector:@selector(tableView:didEndDisplayingHeaderView:forSection:)]) {
711 + [self.originalDelegate tableView:self.nativeTableView didEndDisplayingHeaderView:view forSection:section];
712 + }
713 +}
714 +
715 +
716 +-(void)tableView:(UITableView *)tableView willDisplayFooterView:(UIView *)view forSection:(NSInteger)section {
717 +
718 + if ([self.originalDelegate respondsToSelector:@selector(tableView:willDisplayFooterView:forSection:)]) {
719 + [self.originalDelegate tableView:self.nativeTableView willDisplayFooterView:view forSection:section];
720 + }
721 +}
722 +
723 +
724 +-(void)tableView:(UITableView *)tableView didEndDisplayingFooterView:(UIView *)view forSection:(NSInteger)section {
725 + if ([self.originalDelegate respondsToSelector:@selector(tableView:didEndDisplayingFooterView:forSection:)]) {
726 + [self.originalDelegate tableView:self.nativeTableView didEndDisplayingFooterView:view forSection:section];
727 + }
728 +}
729 +
730 +
731 +@end
1 +//
2 +// WLNativeVideoTableViewCell.h
3 +// DemoApp
4 +//
5 +// Created by Nick Xirotyris on 2/2/16.
6 +// Copyright © 2016 YC. All rights reserved.
7 +//
8 +
9 +#import <UIKit/UIKit.h>
10 +
11 +@interface WLNativeVideoTableViewCell : UITableViewCell
12 +
13 +@end
1 +//
2 +// WLNativeVideoTableViewCell.m
3 +// DemoApp
4 +//
5 +// Created by Nick Xirotyris on 2/2/16.
6 +// Copyright © 2016 YC. All rights reserved.
7 +//
8 +
9 +#import "WLNativeVideoTableViewCell.h"
10 +#import <AVFoundation/AVFoundation.h>
11 +
12 +
13 +@implementation WLNativeVideoTableViewCell
14 +
15 +- (void)awakeFromNib {
16 + // Initialization code
17 + [super awakeFromNib];
18 +
19 +
20 +}
21 +
22 +- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
23 + [super setSelected:selected animated:animated];
24 +
25 + // Configure the view for the selected state
26 +}
27 +
28 +@end
1 +<?xml version="1.0" encoding="UTF-8" standalone="no"?>
2 +<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="9531" systemVersion="15D21" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES">
3 + <dependencies>
4 + <deployment identifier="iOS"/>
5 + <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="9529"/>
6 + </dependencies>
7 + <objects>
8 + <placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
9 + <placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
10 + <view contentMode="scaleToFill" id="iN0-l3-epB" customClass="WLNativeVideoTableViewCell">
11 + <rect key="frame" x="0.0" y="0.0" width="260" height="260"/>
12 + <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
13 + <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
14 + <freeformSimulatedSizeMetrics key="simulatedDestinationMetrics"/>
15 + <point key="canvasLocation" x="476.5" y="376"/>
16 + </view>
17 + </objects>
18 +</document>
1 +// !$*UTF8*$!
2 +{
3 + archiveVersion = 1;
4 + classes = {
5 + };
6 + objectVersion = 55;
7 + objects = {
8 +
9 +/* Begin PBXBuildFile section */
10 + E6D8DE6D27A942010006A3A9 /* WarplySDKFrameworkIOS.docc in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DE6C27A942010006A3A9 /* WarplySDKFrameworkIOS.docc */; };
11 + E6D8DE6E27A942010006A3A9 /* WarplySDKFrameworkIOS.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DE6B27A942010006A3A9 /* WarplySDKFrameworkIOS.h */; settings = {ATTRIBUTES = (Public, ); }; };
12 + E6D8DEEE27A942920006A3A9 /* WarplyReactMethods.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DE7527A942910006A3A9 /* WarplyReactMethods.m */; };
13 + E6D8DEEF27A942920006A3A9 /* WarplyReactMethods.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DE7627A942910006A3A9 /* WarplyReactMethods.h */; };
14 + E6D8DEF027A942920006A3A9 /* WLNativeAdCollectionViewCell.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DE7927A942910006A3A9 /* WLNativeAdCollectionViewCell.h */; };
15 + E6D8DEF127A942920006A3A9 /* WLNativeVideoTableViewCell.xib in Resources */ = {isa = PBXBuildFile; fileRef = E6D8DE7A27A942910006A3A9 /* WLNativeVideoTableViewCell.xib */; };
16 + E6D8DEF227A942920006A3A9 /* WLNativeAdTableViewCell.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DE7B27A942910006A3A9 /* WLNativeAdTableViewCell.h */; };
17 + E6D8DEF327A942920006A3A9 /* WLNativeVideoTableViewCell.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DE7C27A942910006A3A9 /* WLNativeVideoTableViewCell.m */; };
18 + E6D8DEF427A942920006A3A9 /* WLCustomNativeCollectionViewCell.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DE7D27A942910006A3A9 /* WLCustomNativeCollectionViewCell.m */; };
19 + E6D8DEF527A942920006A3A9 /* WLNativeAdsTableMode.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DE7E27A942910006A3A9 /* WLNativeAdsTableMode.m */; };
20 + E6D8DEF627A942920006A3A9 /* WLCustomNativeAdTableViewCell.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DE7F27A942910006A3A9 /* WLCustomNativeAdTableViewCell.h */; };
21 + E6D8DEF727A942920006A3A9 /* WLNativeAdsCollectionMode.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DE8027A942910006A3A9 /* WLNativeAdsCollectionMode.m */; };
22 + E6D8DEF827A942920006A3A9 /* WLNativeAdTableViewCell.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DE8127A942910006A3A9 /* WLNativeAdTableViewCell.m */; };
23 + E6D8DEF927A942920006A3A9 /* WLNativeAdCollectionViewCell.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DE8227A942910006A3A9 /* WLNativeAdCollectionViewCell.m */; };
24 + E6D8DEFA27A942920006A3A9 /* WLNativeAdTableViewCell.xib in Resources */ = {isa = PBXBuildFile; fileRef = E6D8DE8327A942910006A3A9 /* WLNativeAdTableViewCell.xib */; };
25 + E6D8DEFB27A942920006A3A9 /* WLNativeAdCollectionViewCell.xib in Resources */ = {isa = PBXBuildFile; fileRef = E6D8DE8427A942910006A3A9 /* WLNativeAdCollectionViewCell.xib */; };
26 + E6D8DEFC27A942920006A3A9 /* WLCustomNativeAdTableViewCell.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DE8527A942910006A3A9 /* WLCustomNativeAdTableViewCell.m */; };
27 + E6D8DEFD27A942920006A3A9 /* WLNativeAdsTableMode.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DE8627A942910006A3A9 /* WLNativeAdsTableMode.h */; };
28 + E6D8DEFE27A942920006A3A9 /* WLCustomNativeCollectionViewCell.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DE8727A942910006A3A9 /* WLCustomNativeCollectionViewCell.h */; };
29 + E6D8DEFF27A942920006A3A9 /* WLNativeVideoTableViewCell.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DE8827A942910006A3A9 /* WLNativeVideoTableViewCell.h */; };
30 + E6D8DF0027A942920006A3A9 /* WLNativeAdsCollectionMode.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DE8927A942910006A3A9 /* WLNativeAdsCollectionMode.h */; };
31 + E6D8DF0127A942920006A3A9 /* WLBeacon.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DE8B27A942910006A3A9 /* WLBeacon.h */; };
32 + E6D8DF0227A942920006A3A9 /* WLBaseItem.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DE8C27A942910006A3A9 /* WLBaseItem.h */; };
33 + E6D8DF0327A942920006A3A9 /* WLInboxItemViewController.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DE8D27A942910006A3A9 /* WLInboxItemViewController.h */; };
34 + E6D8DF0427A942920006A3A9 /* WLInboxItem.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DE8E27A942910006A3A9 /* WLInboxItem.m */; };
35 + E6D8DF0527A942920006A3A9 /* WLAPSItem.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DE8F27A942910006A3A9 /* WLAPSItem.h */; };
36 + E6D8DF0627A942920006A3A9 /* WLBeacon.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DE9027A942910006A3A9 /* WLBeacon.m */; };
37 + E6D8DF0727A942920006A3A9 /* WLInboxItemViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DE9127A942910006A3A9 /* WLInboxItemViewController.m */; };
38 + E6D8DF0827A942920006A3A9 /* WLBaseItem.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DE9227A942910006A3A9 /* WLBaseItem.m */; };
39 + E6D8DF0927A942920006A3A9 /* WLInboxItem.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DE9327A942910006A3A9 /* WLInboxItem.h */; };
40 + E6D8DF0A27A942920006A3A9 /* WLAPSItem.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DE9427A942910006A3A9 /* WLAPSItem.m */; };
41 + E6D8DF0B27A942920006A3A9 /* WLEvent.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DE9527A942910006A3A9 /* WLEvent.m */; };
42 + E6D8DF0C27A942920006A3A9 /* warp_white_back_button@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = E6D8DE9727A942910006A3A9 /* warp_white_back_button@2x.png */; };
43 + E6D8DF0D27A942920006A3A9 /* warp_white_forward_button.png in Resources */ = {isa = PBXBuildFile; fileRef = E6D8DE9827A942910006A3A9 /* warp_white_forward_button.png */; };
44 + E6D8DF0E27A942920006A3A9 /* warp_white_back_button.png in Resources */ = {isa = PBXBuildFile; fileRef = E6D8DE9927A942910006A3A9 /* warp_white_back_button.png */; };
45 + E6D8DF0F27A942920006A3A9 /* warp_white_close_button@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = E6D8DE9A27A942910006A3A9 /* warp_white_close_button@2x.png */; };
46 + E6D8DF1027A942920006A3A9 /* warp_white_forward_button@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = E6D8DE9B27A942910006A3A9 /* warp_white_forward_button@2x.png */; };
47 + E6D8DF1127A942920006A3A9 /* warp_white_close_button.png in Resources */ = {isa = PBXBuildFile; fileRef = E6D8DE9C27A942910006A3A9 /* warp_white_close_button.png */; };
48 + E6D8DF1227A942920006A3A9 /* WLPushManager.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DE9E27A942910006A3A9 /* WLPushManager.m */; };
49 + E6D8DF1327A942920006A3A9 /* WLBeaconManager.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DE9F27A942910006A3A9 /* WLBeaconManager.m */; };
50 + E6D8DF1427A942920006A3A9 /* WLLocationManager.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEA027A942910006A3A9 /* WLLocationManager.m */; };
51 + E6D8DF1527A942920006A3A9 /* WLAnalyticsManager.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEA127A942910006A3A9 /* WLAnalyticsManager.h */; };
52 + E6D8DF1627A942920006A3A9 /* WLUserManager.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEA227A942910006A3A9 /* WLUserManager.h */; };
53 + E6D8DF1727A942920006A3A9 /* WLBeaconManager.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEA327A942910006A3A9 /* WLBeaconManager.h */; };
54 + E6D8DF1827A942920006A3A9 /* WLPushManager.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEA427A942910006A3A9 /* WLPushManager.h */; };
55 + E6D8DF1927A942920006A3A9 /* WLAnalyticsManager.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEA527A942910006A3A9 /* WLAnalyticsManager.m */; };
56 + E6D8DF1A27A942920006A3A9 /* WLLocationManager.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEA627A942910006A3A9 /* WLLocationManager.h */; };
57 + E6D8DF1B27A942920006A3A9 /* WLUserManager.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEA727A942910006A3A9 /* WLUserManager.m */; };
58 + E6D8DF1C27A942920006A3A9 /* WLUtils.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEA927A942910006A3A9 /* WLUtils.m */; };
59 + E6D8DF1D27A942920006A3A9 /* UIViewController+WLAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEAA27A942910006A3A9 /* UIViewController+WLAdditions.h */; };
60 + E6D8DF1E27A942920006A3A9 /* UIViewController+WLAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEAB27A942910006A3A9 /* UIViewController+WLAdditions.m */; };
61 + E6D8DF1F27A942920006A3A9 /* WLUtils.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEAC27A942910006A3A9 /* WLUtils.h */; };
62 + E6D8DF2027A942920006A3A9 /* Warply.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEAD27A942910006A3A9 /* Warply.m */; };
63 + E6D8DF2127A942920006A3A9 /* WLAPPActionHandler.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEAF27A942910006A3A9 /* WLAPPActionHandler.m */; };
64 + E6D8DF2227A942920006A3A9 /* WLSMSActionHanlder.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEB027A942910006A3A9 /* WLSMSActionHanlder.h */; };
65 + E6D8DF2327A942920006A3A9 /* WLSMSActionHandlerDeprecated.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEB127A942910006A3A9 /* WLSMSActionHandlerDeprecated.m */; };
66 + E6D8DF2427A942920006A3A9 /* WLSMSActionHandlerDeprecated.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEB227A942910006A3A9 /* WLSMSActionHandlerDeprecated.h */; };
67 + E6D8DF2527A942920006A3A9 /* WLSMSActionHanlder.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEB327A942910006A3A9 /* WLSMSActionHanlder.m */; };
68 + E6D8DF2627A942920006A3A9 /* WLAPPActionHandler.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEB427A942910006A3A9 /* WLAPPActionHandler.h */; };
69 + E6D8DF2727A942920006A3A9 /* WLGlobals.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEB527A942910006A3A9 /* WLGlobals.h */; };
70 + E6D8DF2827A942920006A3A9 /* NSString+SSToolkitAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEB827A942910006A3A9 /* NSString+SSToolkitAdditions.h */; };
71 + E6D8DF2927A942920006A3A9 /* NSData+SSToolkitAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEB927A942910006A3A9 /* NSData+SSToolkitAdditions.m */; };
72 + E6D8DF2A27A942920006A3A9 /* NSData+SSToolkitAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEBA27A942910006A3A9 /* NSData+SSToolkitAdditions.h */; };
73 + E6D8DF2B27A942920006A3A9 /* NSString+SSToolkitAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEBB27A942910006A3A9 /* NSString+SSToolkitAdditions.m */; };
74 + E6D8DF2C27A942920006A3A9 /* UIProgressView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEBD27A942910006A3A9 /* UIProgressView+AFNetworking.m */; };
75 + E6D8DF2D27A942920006A3A9 /* UIButton+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEBE27A942910006A3A9 /* UIButton+AFNetworking.h */; };
76 + E6D8DF2E27A942920006A3A9 /* UIRefreshControl+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEBF27A942910006A3A9 /* UIRefreshControl+AFNetworking.m */; };
77 + E6D8DF2F27A942920006A3A9 /* UIImageView+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEC027A942910006A3A9 /* UIImageView+AFNetworking.h */; };
78 + E6D8DF3027A942920006A3A9 /* AFImageDownloader.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEC127A942910006A3A9 /* AFImageDownloader.h */; };
79 + E6D8DF3127A942920006A3A9 /* AFNetworkActivityIndicatorManager.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEC227A942910006A3A9 /* AFNetworkActivityIndicatorManager.m */; };
80 + E6D8DF3227A942920006A3A9 /* AFAutoPurgingImageCache.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEC327A942910006A3A9 /* AFAutoPurgingImageCache.h */; };
81 + E6D8DF3327A942920006A3A9 /* UIWebView+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEC427A942910006A3A9 /* UIWebView+AFNetworking.h */; };
82 + E6D8DF3427A942920006A3A9 /* UIActivityIndicatorView+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEC527A942910006A3A9 /* UIActivityIndicatorView+AFNetworking.h */; };
83 + E6D8DF3527A942920006A3A9 /* UIImage+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEC627A942910006A3A9 /* UIImage+AFNetworking.h */; };
84 + E6D8DF3627A942920006A3A9 /* UIProgressView+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEC727A942910006A3A9 /* UIProgressView+AFNetworking.h */; };
85 + E6D8DF3727A942920006A3A9 /* UIImageView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEC827A942910006A3A9 /* UIImageView+AFNetworking.m */; };
86 + E6D8DF3827A942920006A3A9 /* UIKit+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEC927A942910006A3A9 /* UIKit+AFNetworking.h */; };
87 + E6D8DF3927A942920006A3A9 /* UIRefreshControl+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DECA27A942910006A3A9 /* UIRefreshControl+AFNetworking.h */; };
88 + E6D8DF3A27A942920006A3A9 /* UIButton+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DECB27A942910006A3A9 /* UIButton+AFNetworking.m */; };
89 + E6D8DF3B27A942920006A3A9 /* UIActivityIndicatorView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DECC27A942910006A3A9 /* UIActivityIndicatorView+AFNetworking.m */; };
90 + E6D8DF3C27A942920006A3A9 /* UIWebView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DECD27A942910006A3A9 /* UIWebView+AFNetworking.m */; };
91 + E6D8DF3D27A942920006A3A9 /* AFAutoPurgingImageCache.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DECE27A942910006A3A9 /* AFAutoPurgingImageCache.m */; };
92 + E6D8DF3E27A942920006A3A9 /* AFNetworkActivityIndicatorManager.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DECF27A942910006A3A9 /* AFNetworkActivityIndicatorManager.h */; };
93 + E6D8DF3F27A942920006A3A9 /* AFImageDownloader.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DED027A942910006A3A9 /* AFImageDownloader.m */; };
94 + E6D8DF4027A942920006A3A9 /* AFSecurityPolicy.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DED227A942910006A3A9 /* AFSecurityPolicy.h */; };
95 + E6D8DF4127A942920006A3A9 /* AFNetworkReachabilityManager.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DED327A942910006A3A9 /* AFNetworkReachabilityManager.h */; };
96 + E6D8DF4227A942920006A3A9 /* AFURLSessionManager.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DED427A942910006A3A9 /* AFURLSessionManager.h */; };
97 + E6D8DF4327A942920006A3A9 /* AFURLRequestSerialization.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DED527A942910006A3A9 /* AFURLRequestSerialization.h */; };
98 + E6D8DF4427A942920006A3A9 /* AFURLResponseSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DED627A942910006A3A9 /* AFURLResponseSerialization.m */; };
99 + E6D8DF4527A942920006A3A9 /* AFHTTPSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DED727A942910006A3A9 /* AFHTTPSessionManager.m */; };
100 + E6D8DF4627A942920006A3A9 /* AFURLResponseSerialization.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DED827A942910006A3A9 /* AFURLResponseSerialization.h */; };
101 + E6D8DF4727A942920006A3A9 /* AFURLSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DED927A942910006A3A9 /* AFURLSessionManager.m */; };
102 + E6D8DF4827A942920006A3A9 /* AFURLRequestSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEDA27A942910006A3A9 /* AFURLRequestSerialization.m */; };
103 + E6D8DF4927A942920006A3A9 /* AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEDB27A942910006A3A9 /* AFNetworking.h */; };
104 + E6D8DF4A27A942920006A3A9 /* AFNetworkReachabilityManager.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEDC27A942910006A3A9 /* AFNetworkReachabilityManager.m */; };
105 + E6D8DF4B27A942920006A3A9 /* AFSecurityPolicy.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEDD27A942910006A3A9 /* AFSecurityPolicy.m */; };
106 + E6D8DF4C27A942920006A3A9 /* AFHTTPSessionManager.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEDE27A942910006A3A9 /* AFHTTPSessionManager.h */; };
107 + E6D8DF4D27A942920006A3A9 /* FMDatabase.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEE027A942910006A3A9 /* FMDatabase.h */; };
108 + E6D8DF4E27A942920006A3A9 /* FMDatabaseQueue.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEE127A942910006A3A9 /* FMDatabaseQueue.m */; };
109 + E6D8DF4F27A942920006A3A9 /* FMResultSet.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEE227A942910006A3A9 /* FMResultSet.h */; };
110 + E6D8DF5027A942920006A3A9 /* FMDatabasePool.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEE327A942910006A3A9 /* FMDatabasePool.h */; };
111 + E6D8DF5127A942920006A3A9 /* FMDatabaseAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEE427A942910006A3A9 /* FMDatabaseAdditions.m */; };
112 + E6D8DF5227A942920006A3A9 /* FMDatabase.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEE527A942910006A3A9 /* FMDatabase.m */; };
113 + E6D8DF5327A942920006A3A9 /* FMDatabaseQueue.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEE627A942910006A3A9 /* FMDatabaseQueue.h */; };
114 + E6D8DF5427A942920006A3A9 /* FMDB.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEE727A942910006A3A9 /* FMDB.h */; };
115 + E6D8DF5527A942920006A3A9 /* FMDatabaseAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEE827A942910006A3A9 /* FMDatabaseAdditions.h */; };
116 + E6D8DF5627A942920006A3A9 /* FMDatabasePool.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEE927A942910006A3A9 /* FMDatabasePool.m */; };
117 + E6D8DF5727A942920006A3A9 /* FMResultSet.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEEA27A942910006A3A9 /* FMResultSet.m */; };
118 + E6D8DF5827A942920006A3A9 /* WLEvent.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEEB27A942910006A3A9 /* WLEvent.h */; };
119 + E6D8DF5927A942920006A3A9 /* Warply.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEEC27A942910006A3A9 /* Warply.h */; };
120 + E6D8DF5A27A942920006A3A9 /* Media.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = E6D8DEED27A942920006A3A9 /* Media.xcassets */; };
121 + E6D8DF5F27A9429E0006A3A9 /* ProfileViewInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DF5B27A9429E0006A3A9 /* ProfileViewInterface.swift */; };
122 + E6D8DF6027A9429E0006A3A9 /* MyApi.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DF5C27A9429E0006A3A9 /* MyApi.m */; };
123 + E6D8DF6127A9429E0006A3A9 /* ProfileView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DF5D27A9429E0006A3A9 /* ProfileView.swift */; };
124 + E6D8DF6227A9429E0006A3A9 /* MyApi.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DF5E27A9429E0006A3A9 /* MyApi.h */; settings = {ATTRIBUTES = (Public, ); }; };
125 +/* End PBXBuildFile section */
126 +
127 +/* Begin PBXFileReference section */
128 + E6D8DE6827A942010006A3A9 /* WarplySDKFrameworkIOS.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = WarplySDKFrameworkIOS.framework; sourceTree = BUILT_PRODUCTS_DIR; };
129 + E6D8DE6B27A942010006A3A9 /* WarplySDKFrameworkIOS.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = WarplySDKFrameworkIOS.h; sourceTree = "<group>"; };
130 + E6D8DE6C27A942010006A3A9 /* WarplySDKFrameworkIOS.docc */ = {isa = PBXFileReference; lastKnownFileType = folder.documentationcatalog; path = WarplySDKFrameworkIOS.docc; sourceTree = "<group>"; };
131 + E6D8DE7527A942910006A3A9 /* WarplyReactMethods.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WarplyReactMethods.m; sourceTree = "<group>"; };
132 + E6D8DE7627A942910006A3A9 /* WarplyReactMethods.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WarplyReactMethods.h; sourceTree = "<group>"; };
133 + E6D8DE7927A942910006A3A9 /* WLNativeAdCollectionViewCell.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLNativeAdCollectionViewCell.h; sourceTree = "<group>"; };
134 + E6D8DE7A27A942910006A3A9 /* WLNativeVideoTableViewCell.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = WLNativeVideoTableViewCell.xib; sourceTree = "<group>"; };
135 + E6D8DE7B27A942910006A3A9 /* WLNativeAdTableViewCell.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLNativeAdTableViewCell.h; sourceTree = "<group>"; };
136 + E6D8DE7C27A942910006A3A9 /* WLNativeVideoTableViewCell.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLNativeVideoTableViewCell.m; sourceTree = "<group>"; };
137 + E6D8DE7D27A942910006A3A9 /* WLCustomNativeCollectionViewCell.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLCustomNativeCollectionViewCell.m; sourceTree = "<group>"; };
138 + E6D8DE7E27A942910006A3A9 /* WLNativeAdsTableMode.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLNativeAdsTableMode.m; sourceTree = "<group>"; };
139 + E6D8DE7F27A942910006A3A9 /* WLCustomNativeAdTableViewCell.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLCustomNativeAdTableViewCell.h; sourceTree = "<group>"; };
140 + E6D8DE8027A942910006A3A9 /* WLNativeAdsCollectionMode.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLNativeAdsCollectionMode.m; sourceTree = "<group>"; };
141 + E6D8DE8127A942910006A3A9 /* WLNativeAdTableViewCell.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLNativeAdTableViewCell.m; sourceTree = "<group>"; };
142 + E6D8DE8227A942910006A3A9 /* WLNativeAdCollectionViewCell.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLNativeAdCollectionViewCell.m; sourceTree = "<group>"; };
143 + E6D8DE8327A942910006A3A9 /* WLNativeAdTableViewCell.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = WLNativeAdTableViewCell.xib; sourceTree = "<group>"; };
144 + E6D8DE8427A942910006A3A9 /* WLNativeAdCollectionViewCell.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = WLNativeAdCollectionViewCell.xib; sourceTree = "<group>"; };
145 + E6D8DE8527A942910006A3A9 /* WLCustomNativeAdTableViewCell.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLCustomNativeAdTableViewCell.m; sourceTree = "<group>"; };
146 + E6D8DE8627A942910006A3A9 /* WLNativeAdsTableMode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLNativeAdsTableMode.h; sourceTree = "<group>"; };
147 + E6D8DE8727A942910006A3A9 /* WLCustomNativeCollectionViewCell.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLCustomNativeCollectionViewCell.h; sourceTree = "<group>"; };
148 + E6D8DE8827A942910006A3A9 /* WLNativeVideoTableViewCell.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLNativeVideoTableViewCell.h; sourceTree = "<group>"; };
149 + E6D8DE8927A942910006A3A9 /* WLNativeAdsCollectionMode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLNativeAdsCollectionMode.h; sourceTree = "<group>"; };
150 + E6D8DE8B27A942910006A3A9 /* WLBeacon.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLBeacon.h; sourceTree = "<group>"; };
151 + E6D8DE8C27A942910006A3A9 /* WLBaseItem.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLBaseItem.h; sourceTree = "<group>"; };
152 + E6D8DE8D27A942910006A3A9 /* WLInboxItemViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLInboxItemViewController.h; sourceTree = "<group>"; };
153 + E6D8DE8E27A942910006A3A9 /* WLInboxItem.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLInboxItem.m; sourceTree = "<group>"; };
154 + E6D8DE8F27A942910006A3A9 /* WLAPSItem.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLAPSItem.h; sourceTree = "<group>"; };
155 + E6D8DE9027A942910006A3A9 /* WLBeacon.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLBeacon.m; sourceTree = "<group>"; };
156 + E6D8DE9127A942910006A3A9 /* WLInboxItemViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLInboxItemViewController.m; sourceTree = "<group>"; };
157 + E6D8DE9227A942910006A3A9 /* WLBaseItem.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLBaseItem.m; sourceTree = "<group>"; };
158 + E6D8DE9327A942910006A3A9 /* WLInboxItem.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLInboxItem.h; sourceTree = "<group>"; };
159 + E6D8DE9427A942910006A3A9 /* WLAPSItem.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLAPSItem.m; sourceTree = "<group>"; };
160 + E6D8DE9527A942910006A3A9 /* WLEvent.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLEvent.m; sourceTree = "<group>"; };
161 + E6D8DE9727A942910006A3A9 /* warp_white_back_button@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "warp_white_back_button@2x.png"; sourceTree = "<group>"; };
162 + E6D8DE9827A942910006A3A9 /* warp_white_forward_button.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = warp_white_forward_button.png; sourceTree = "<group>"; };
163 + E6D8DE9927A942910006A3A9 /* warp_white_back_button.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = warp_white_back_button.png; sourceTree = "<group>"; };
164 + E6D8DE9A27A942910006A3A9 /* warp_white_close_button@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "warp_white_close_button@2x.png"; sourceTree = "<group>"; };
165 + E6D8DE9B27A942910006A3A9 /* warp_white_forward_button@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "warp_white_forward_button@2x.png"; sourceTree = "<group>"; };
166 + E6D8DE9C27A942910006A3A9 /* warp_white_close_button.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = warp_white_close_button.png; sourceTree = "<group>"; };
167 + E6D8DE9E27A942910006A3A9 /* WLPushManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLPushManager.m; sourceTree = "<group>"; };
168 + E6D8DE9F27A942910006A3A9 /* WLBeaconManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLBeaconManager.m; sourceTree = "<group>"; };
169 + E6D8DEA027A942910006A3A9 /* WLLocationManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLLocationManager.m; sourceTree = "<group>"; };
170 + E6D8DEA127A942910006A3A9 /* WLAnalyticsManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLAnalyticsManager.h; sourceTree = "<group>"; };
171 + E6D8DEA227A942910006A3A9 /* WLUserManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLUserManager.h; sourceTree = "<group>"; };
172 + E6D8DEA327A942910006A3A9 /* WLBeaconManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLBeaconManager.h; sourceTree = "<group>"; };
173 + E6D8DEA427A942910006A3A9 /* WLPushManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLPushManager.h; sourceTree = "<group>"; };
174 + E6D8DEA527A942910006A3A9 /* WLAnalyticsManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLAnalyticsManager.m; sourceTree = "<group>"; };
175 + E6D8DEA627A942910006A3A9 /* WLLocationManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLLocationManager.h; sourceTree = "<group>"; };
176 + E6D8DEA727A942910006A3A9 /* WLUserManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLUserManager.m; sourceTree = "<group>"; };
177 + E6D8DEA927A942910006A3A9 /* WLUtils.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLUtils.m; sourceTree = "<group>"; };
178 + E6D8DEAA27A942910006A3A9 /* UIViewController+WLAdditions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIViewController+WLAdditions.h"; sourceTree = "<group>"; };
179 + E6D8DEAB27A942910006A3A9 /* UIViewController+WLAdditions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIViewController+WLAdditions.m"; sourceTree = "<group>"; };
180 + E6D8DEAC27A942910006A3A9 /* WLUtils.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLUtils.h; sourceTree = "<group>"; };
181 + E6D8DEAD27A942910006A3A9 /* Warply.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = Warply.m; sourceTree = "<group>"; };
182 + E6D8DEAF27A942910006A3A9 /* WLAPPActionHandler.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLAPPActionHandler.m; sourceTree = "<group>"; };
183 + E6D8DEB027A942910006A3A9 /* WLSMSActionHanlder.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLSMSActionHanlder.h; sourceTree = "<group>"; };
184 + E6D8DEB127A942910006A3A9 /* WLSMSActionHandlerDeprecated.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLSMSActionHandlerDeprecated.m; sourceTree = "<group>"; };
185 + E6D8DEB227A942910006A3A9 /* WLSMSActionHandlerDeprecated.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLSMSActionHandlerDeprecated.h; sourceTree = "<group>"; };
186 + E6D8DEB327A942910006A3A9 /* WLSMSActionHanlder.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLSMSActionHanlder.m; sourceTree = "<group>"; };
187 + E6D8DEB427A942910006A3A9 /* WLAPPActionHandler.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLAPPActionHandler.h; sourceTree = "<group>"; };
188 + E6D8DEB527A942910006A3A9 /* WLGlobals.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLGlobals.h; sourceTree = "<group>"; };
189 + E6D8DEB827A942910006A3A9 /* NSString+SSToolkitAdditions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSString+SSToolkitAdditions.h"; sourceTree = "<group>"; };
190 + E6D8DEB927A942910006A3A9 /* NSData+SSToolkitAdditions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSData+SSToolkitAdditions.m"; sourceTree = "<group>"; };
191 + E6D8DEBA27A942910006A3A9 /* NSData+SSToolkitAdditions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSData+SSToolkitAdditions.h"; sourceTree = "<group>"; };
192 + E6D8DEBB27A942910006A3A9 /* NSString+SSToolkitAdditions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSString+SSToolkitAdditions.m"; sourceTree = "<group>"; };
193 + E6D8DEBD27A942910006A3A9 /* UIProgressView+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIProgressView+AFNetworking.m"; sourceTree = "<group>"; };
194 + E6D8DEBE27A942910006A3A9 /* UIButton+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIButton+AFNetworking.h"; sourceTree = "<group>"; };
195 + E6D8DEBF27A942910006A3A9 /* UIRefreshControl+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIRefreshControl+AFNetworking.m"; sourceTree = "<group>"; };
196 + E6D8DEC027A942910006A3A9 /* UIImageView+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIImageView+AFNetworking.h"; sourceTree = "<group>"; };
197 + E6D8DEC127A942910006A3A9 /* AFImageDownloader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFImageDownloader.h; sourceTree = "<group>"; };
198 + E6D8DEC227A942910006A3A9 /* AFNetworkActivityIndicatorManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFNetworkActivityIndicatorManager.m; sourceTree = "<group>"; };
199 + E6D8DEC327A942910006A3A9 /* AFAutoPurgingImageCache.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFAutoPurgingImageCache.h; sourceTree = "<group>"; };
200 + E6D8DEC427A942910006A3A9 /* UIWebView+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIWebView+AFNetworking.h"; sourceTree = "<group>"; };
201 + E6D8DEC527A942910006A3A9 /* UIActivityIndicatorView+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIActivityIndicatorView+AFNetworking.h"; sourceTree = "<group>"; };
202 + E6D8DEC627A942910006A3A9 /* UIImage+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIImage+AFNetworking.h"; sourceTree = "<group>"; };
203 + E6D8DEC727A942910006A3A9 /* UIProgressView+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIProgressView+AFNetworking.h"; sourceTree = "<group>"; };
204 + E6D8DEC827A942910006A3A9 /* UIImageView+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIImageView+AFNetworking.m"; sourceTree = "<group>"; };
205 + E6D8DEC927A942910006A3A9 /* UIKit+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIKit+AFNetworking.h"; sourceTree = "<group>"; };
206 + E6D8DECA27A942910006A3A9 /* UIRefreshControl+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIRefreshControl+AFNetworking.h"; sourceTree = "<group>"; };
207 + E6D8DECB27A942910006A3A9 /* UIButton+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIButton+AFNetworking.m"; sourceTree = "<group>"; };
208 + E6D8DECC27A942910006A3A9 /* UIActivityIndicatorView+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIActivityIndicatorView+AFNetworking.m"; sourceTree = "<group>"; };
209 + E6D8DECD27A942910006A3A9 /* UIWebView+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIWebView+AFNetworking.m"; sourceTree = "<group>"; };
210 + E6D8DECE27A942910006A3A9 /* AFAutoPurgingImageCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFAutoPurgingImageCache.m; sourceTree = "<group>"; };
211 + E6D8DECF27A942910006A3A9 /* AFNetworkActivityIndicatorManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFNetworkActivityIndicatorManager.h; sourceTree = "<group>"; };
212 + E6D8DED027A942910006A3A9 /* AFImageDownloader.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFImageDownloader.m; sourceTree = "<group>"; };
213 + E6D8DED227A942910006A3A9 /* AFSecurityPolicy.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFSecurityPolicy.h; sourceTree = "<group>"; };
214 + E6D8DED327A942910006A3A9 /* AFNetworkReachabilityManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFNetworkReachabilityManager.h; sourceTree = "<group>"; };
215 + E6D8DED427A942910006A3A9 /* AFURLSessionManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFURLSessionManager.h; sourceTree = "<group>"; };
216 + E6D8DED527A942910006A3A9 /* AFURLRequestSerialization.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFURLRequestSerialization.h; sourceTree = "<group>"; };
217 + E6D8DED627A942910006A3A9 /* AFURLResponseSerialization.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFURLResponseSerialization.m; sourceTree = "<group>"; };
218 + E6D8DED727A942910006A3A9 /* AFHTTPSessionManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFHTTPSessionManager.m; sourceTree = "<group>"; };
219 + E6D8DED827A942910006A3A9 /* AFURLResponseSerialization.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFURLResponseSerialization.h; sourceTree = "<group>"; };
220 + E6D8DED927A942910006A3A9 /* AFURLSessionManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFURLSessionManager.m; sourceTree = "<group>"; };
221 + E6D8DEDA27A942910006A3A9 /* AFURLRequestSerialization.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFURLRequestSerialization.m; sourceTree = "<group>"; };
222 + E6D8DEDB27A942910006A3A9 /* AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFNetworking.h; sourceTree = "<group>"; };
223 + E6D8DEDC27A942910006A3A9 /* AFNetworkReachabilityManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFNetworkReachabilityManager.m; sourceTree = "<group>"; };
224 + E6D8DEDD27A942910006A3A9 /* AFSecurityPolicy.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFSecurityPolicy.m; sourceTree = "<group>"; };
225 + E6D8DEDE27A942910006A3A9 /* AFHTTPSessionManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFHTTPSessionManager.h; sourceTree = "<group>"; };
226 + E6D8DEE027A942910006A3A9 /* FMDatabase.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMDatabase.h; sourceTree = "<group>"; };
227 + E6D8DEE127A942910006A3A9 /* FMDatabaseQueue.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDatabaseQueue.m; sourceTree = "<group>"; };
228 + E6D8DEE227A942910006A3A9 /* FMResultSet.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMResultSet.h; sourceTree = "<group>"; };
229 + E6D8DEE327A942910006A3A9 /* FMDatabasePool.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMDatabasePool.h; sourceTree = "<group>"; };
230 + E6D8DEE427A942910006A3A9 /* FMDatabaseAdditions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDatabaseAdditions.m; sourceTree = "<group>"; };
231 + E6D8DEE527A942910006A3A9 /* FMDatabase.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDatabase.m; sourceTree = "<group>"; };
232 + E6D8DEE627A942910006A3A9 /* FMDatabaseQueue.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMDatabaseQueue.h; sourceTree = "<group>"; };
233 + E6D8DEE727A942910006A3A9 /* FMDB.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMDB.h; sourceTree = "<group>"; };
234 + E6D8DEE827A942910006A3A9 /* FMDatabaseAdditions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMDatabaseAdditions.h; sourceTree = "<group>"; };
235 + E6D8DEE927A942910006A3A9 /* FMDatabasePool.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDatabasePool.m; sourceTree = "<group>"; };
236 + E6D8DEEA27A942910006A3A9 /* FMResultSet.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMResultSet.m; sourceTree = "<group>"; };
237 + E6D8DEEB27A942910006A3A9 /* WLEvent.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLEvent.h; sourceTree = "<group>"; };
238 + E6D8DEEC27A942910006A3A9 /* Warply.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Warply.h; sourceTree = "<group>"; };
239 + E6D8DEED27A942920006A3A9 /* Media.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Media.xcassets; sourceTree = SOURCE_ROOT; };
240 + E6D8DF5B27A9429E0006A3A9 /* ProfileViewInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ProfileViewInterface.swift; sourceTree = "<group>"; };
241 + E6D8DF5C27A9429E0006A3A9 /* MyApi.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MyApi.m; sourceTree = "<group>"; };
242 + E6D8DF5D27A9429E0006A3A9 /* ProfileView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ProfileView.swift; sourceTree = "<group>"; };
243 + E6D8DF5E27A9429E0006A3A9 /* MyApi.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MyApi.h; sourceTree = "<group>"; };
244 +/* End PBXFileReference section */
245 +
246 +/* Begin PBXFrameworksBuildPhase section */
247 + E6D8DE6527A942010006A3A9 /* Frameworks */ = {
248 + isa = PBXFrameworksBuildPhase;
249 + buildActionMask = 2147483647;
250 + files = (
251 + );
252 + runOnlyForDeploymentPostprocessing = 0;
253 + };
254 +/* End PBXFrameworksBuildPhase section */
255 +
256 +/* Begin PBXGroup section */
257 + E6D8DE5E27A942000006A3A9 = {
258 + isa = PBXGroup;
259 + children = (
260 + E6D8DE6A27A942010006A3A9 /* WarplySDKFrameworkIOS */,
261 + E6D8DE6927A942010006A3A9 /* Products */,
262 + );
263 + sourceTree = "<group>";
264 + };
265 + E6D8DE6927A942010006A3A9 /* Products */ = {
266 + isa = PBXGroup;
267 + children = (
268 + E6D8DE6827A942010006A3A9 /* WarplySDKFrameworkIOS.framework */,
269 + );
270 + name = Products;
271 + sourceTree = "<group>";
272 + };
273 + E6D8DE6A27A942010006A3A9 /* WarplySDKFrameworkIOS */ = {
274 + isa = PBXGroup;
275 + children = (
276 + E6D8DF5E27A9429E0006A3A9 /* MyApi.h */,
277 + E6D8DF5C27A9429E0006A3A9 /* MyApi.m */,
278 + E6D8DF5D27A9429E0006A3A9 /* ProfileView.swift */,
279 + E6D8DF5B27A9429E0006A3A9 /* ProfileViewInterface.swift */,
280 + E6D8DE7427A942910006A3A9 /* Helpers */,
281 + E6D8DEED27A942920006A3A9 /* Media.xcassets */,
282 + E6D8DE7727A942910006A3A9 /* Warply */,
283 + E6D8DE6B27A942010006A3A9 /* WarplySDKFrameworkIOS.h */,
284 + E6D8DE6C27A942010006A3A9 /* WarplySDKFrameworkIOS.docc */,
285 + );
286 + path = WarplySDKFrameworkIOS;
287 + sourceTree = "<group>";
288 + };
289 + E6D8DE7427A942910006A3A9 /* Helpers */ = {
290 + isa = PBXGroup;
291 + children = (
292 + E6D8DE7527A942910006A3A9 /* WarplyReactMethods.m */,
293 + E6D8DE7627A942910006A3A9 /* WarplyReactMethods.h */,
294 + );
295 + path = Helpers;
296 + sourceTree = SOURCE_ROOT;
297 + };
298 + E6D8DE7727A942910006A3A9 /* Warply */ = {
299 + isa = PBXGroup;
300 + children = (
301 + E6D8DE7827A942910006A3A9 /* nativeAds */,
302 + E6D8DE8A27A942910006A3A9 /* inbox */,
303 + E6D8DE9527A942910006A3A9 /* WLEvent.m */,
304 + E6D8DE9627A942910006A3A9 /* resources */,
305 + E6D8DE9D27A942910006A3A9 /* managers */,
306 + E6D8DEA827A942910006A3A9 /* foundation */,
307 + E6D8DEAD27A942910006A3A9 /* Warply.m */,
308 + E6D8DEAE27A942910006A3A9 /* actions */,
309 + E6D8DEB527A942910006A3A9 /* WLGlobals.h */,
310 + E6D8DEB627A942910006A3A9 /* external */,
311 + E6D8DEEB27A942910006A3A9 /* WLEvent.h */,
312 + E6D8DEEC27A942910006A3A9 /* Warply.h */,
313 + );
314 + path = Warply;
315 + sourceTree = SOURCE_ROOT;
316 + };
317 + E6D8DE7827A942910006A3A9 /* nativeAds */ = {
318 + isa = PBXGroup;
319 + children = (
320 + E6D8DE7927A942910006A3A9 /* WLNativeAdCollectionViewCell.h */,
321 + E6D8DE7A27A942910006A3A9 /* WLNativeVideoTableViewCell.xib */,
322 + E6D8DE7B27A942910006A3A9 /* WLNativeAdTableViewCell.h */,
323 + E6D8DE7C27A942910006A3A9 /* WLNativeVideoTableViewCell.m */,
324 + E6D8DE7D27A942910006A3A9 /* WLCustomNativeCollectionViewCell.m */,
325 + E6D8DE7E27A942910006A3A9 /* WLNativeAdsTableMode.m */,
326 + E6D8DE7F27A942910006A3A9 /* WLCustomNativeAdTableViewCell.h */,
327 + E6D8DE8027A942910006A3A9 /* WLNativeAdsCollectionMode.m */,
328 + E6D8DE8127A942910006A3A9 /* WLNativeAdTableViewCell.m */,
329 + E6D8DE8227A942910006A3A9 /* WLNativeAdCollectionViewCell.m */,
330 + E6D8DE8327A942910006A3A9 /* WLNativeAdTableViewCell.xib */,
331 + E6D8DE8427A942910006A3A9 /* WLNativeAdCollectionViewCell.xib */,
332 + E6D8DE8527A942910006A3A9 /* WLCustomNativeAdTableViewCell.m */,
333 + E6D8DE8627A942910006A3A9 /* WLNativeAdsTableMode.h */,
334 + E6D8DE8727A942910006A3A9 /* WLCustomNativeCollectionViewCell.h */,
335 + E6D8DE8827A942910006A3A9 /* WLNativeVideoTableViewCell.h */,
336 + E6D8DE8927A942910006A3A9 /* WLNativeAdsCollectionMode.h */,
337 + );
338 + path = nativeAds;
339 + sourceTree = "<group>";
340 + };
341 + E6D8DE8A27A942910006A3A9 /* inbox */ = {
342 + isa = PBXGroup;
343 + children = (
344 + E6D8DE8B27A942910006A3A9 /* WLBeacon.h */,
345 + E6D8DE8C27A942910006A3A9 /* WLBaseItem.h */,
346 + E6D8DE8D27A942910006A3A9 /* WLInboxItemViewController.h */,
347 + E6D8DE8E27A942910006A3A9 /* WLInboxItem.m */,
348 + E6D8DE8F27A942910006A3A9 /* WLAPSItem.h */,
349 + E6D8DE9027A942910006A3A9 /* WLBeacon.m */,
350 + E6D8DE9127A942910006A3A9 /* WLInboxItemViewController.m */,
351 + E6D8DE9227A942910006A3A9 /* WLBaseItem.m */,
352 + E6D8DE9327A942910006A3A9 /* WLInboxItem.h */,
353 + E6D8DE9427A942910006A3A9 /* WLAPSItem.m */,
354 + );
355 + path = inbox;
356 + sourceTree = "<group>";
357 + };
358 + E6D8DE9627A942910006A3A9 /* resources */ = {
359 + isa = PBXGroup;
360 + children = (
361 + E6D8DE9727A942910006A3A9 /* warp_white_back_button@2x.png */,
362 + E6D8DE9827A942910006A3A9 /* warp_white_forward_button.png */,
363 + E6D8DE9927A942910006A3A9 /* warp_white_back_button.png */,
364 + E6D8DE9A27A942910006A3A9 /* warp_white_close_button@2x.png */,
365 + E6D8DE9B27A942910006A3A9 /* warp_white_forward_button@2x.png */,
366 + E6D8DE9C27A942910006A3A9 /* warp_white_close_button.png */,
367 + );
368 + path = resources;
369 + sourceTree = "<group>";
370 + };
371 + E6D8DE9D27A942910006A3A9 /* managers */ = {
372 + isa = PBXGroup;
373 + children = (
374 + E6D8DE9E27A942910006A3A9 /* WLPushManager.m */,
375 + E6D8DE9F27A942910006A3A9 /* WLBeaconManager.m */,
376 + E6D8DEA027A942910006A3A9 /* WLLocationManager.m */,
377 + E6D8DEA127A942910006A3A9 /* WLAnalyticsManager.h */,
378 + E6D8DEA227A942910006A3A9 /* WLUserManager.h */,
379 + E6D8DEA327A942910006A3A9 /* WLBeaconManager.h */,
380 + E6D8DEA427A942910006A3A9 /* WLPushManager.h */,
381 + E6D8DEA527A942910006A3A9 /* WLAnalyticsManager.m */,
382 + E6D8DEA627A942910006A3A9 /* WLLocationManager.h */,
383 + E6D8DEA727A942910006A3A9 /* WLUserManager.m */,
384 + );
385 + path = managers;
386 + sourceTree = "<group>";
387 + };
388 + E6D8DEA827A942910006A3A9 /* foundation */ = {
389 + isa = PBXGroup;
390 + children = (
391 + E6D8DEA927A942910006A3A9 /* WLUtils.m */,
392 + E6D8DEAA27A942910006A3A9 /* UIViewController+WLAdditions.h */,
393 + E6D8DEAB27A942910006A3A9 /* UIViewController+WLAdditions.m */,
394 + E6D8DEAC27A942910006A3A9 /* WLUtils.h */,
395 + );
396 + path = foundation;
397 + sourceTree = "<group>";
398 + };
399 + E6D8DEAE27A942910006A3A9 /* actions */ = {
400 + isa = PBXGroup;
401 + children = (
402 + E6D8DEAF27A942910006A3A9 /* WLAPPActionHandler.m */,
403 + E6D8DEB027A942910006A3A9 /* WLSMSActionHanlder.h */,
404 + E6D8DEB127A942910006A3A9 /* WLSMSActionHandlerDeprecated.m */,
405 + E6D8DEB227A942910006A3A9 /* WLSMSActionHandlerDeprecated.h */,
406 + E6D8DEB327A942910006A3A9 /* WLSMSActionHanlder.m */,
407 + E6D8DEB427A942910006A3A9 /* WLAPPActionHandler.h */,
408 + );
409 + path = actions;
410 + sourceTree = "<group>";
411 + };
412 + E6D8DEB627A942910006A3A9 /* external */ = {
413 + isa = PBXGroup;
414 + children = (
415 + E6D8DEB727A942910006A3A9 /* sstoolkit */,
416 + E6D8DEBC27A942910006A3A9 /* UIKit+AFNetworking */,
417 + E6D8DED127A942910006A3A9 /* AFNetworking */,
418 + E6D8DEDF27A942910006A3A9 /* fmdb */,
419 + );
420 + path = external;
421 + sourceTree = "<group>";
422 + };
423 + E6D8DEB727A942910006A3A9 /* sstoolkit */ = {
424 + isa = PBXGroup;
425 + children = (
426 + E6D8DEB827A942910006A3A9 /* NSString+SSToolkitAdditions.h */,
427 + E6D8DEB927A942910006A3A9 /* NSData+SSToolkitAdditions.m */,
428 + E6D8DEBA27A942910006A3A9 /* NSData+SSToolkitAdditions.h */,
429 + E6D8DEBB27A942910006A3A9 /* NSString+SSToolkitAdditions.m */,
430 + );
431 + path = sstoolkit;
432 + sourceTree = "<group>";
433 + };
434 + E6D8DEBC27A942910006A3A9 /* UIKit+AFNetworking */ = {
435 + isa = PBXGroup;
436 + children = (
437 + E6D8DEBD27A942910006A3A9 /* UIProgressView+AFNetworking.m */,
438 + E6D8DEBE27A942910006A3A9 /* UIButton+AFNetworking.h */,
439 + E6D8DEBF27A942910006A3A9 /* UIRefreshControl+AFNetworking.m */,
440 + E6D8DEC027A942910006A3A9 /* UIImageView+AFNetworking.h */,
441 + E6D8DEC127A942910006A3A9 /* AFImageDownloader.h */,
442 + E6D8DEC227A942910006A3A9 /* AFNetworkActivityIndicatorManager.m */,
443 + E6D8DEC327A942910006A3A9 /* AFAutoPurgingImageCache.h */,
444 + E6D8DEC427A942910006A3A9 /* UIWebView+AFNetworking.h */,
445 + E6D8DEC527A942910006A3A9 /* UIActivityIndicatorView+AFNetworking.h */,
446 + E6D8DEC627A942910006A3A9 /* UIImage+AFNetworking.h */,
447 + E6D8DEC727A942910006A3A9 /* UIProgressView+AFNetworking.h */,
448 + E6D8DEC827A942910006A3A9 /* UIImageView+AFNetworking.m */,
449 + E6D8DEC927A942910006A3A9 /* UIKit+AFNetworking.h */,
450 + E6D8DECA27A942910006A3A9 /* UIRefreshControl+AFNetworking.h */,
451 + E6D8DECB27A942910006A3A9 /* UIButton+AFNetworking.m */,
452 + E6D8DECC27A942910006A3A9 /* UIActivityIndicatorView+AFNetworking.m */,
453 + E6D8DECD27A942910006A3A9 /* UIWebView+AFNetworking.m */,
454 + E6D8DECE27A942910006A3A9 /* AFAutoPurgingImageCache.m */,
455 + E6D8DECF27A942910006A3A9 /* AFNetworkActivityIndicatorManager.h */,
456 + E6D8DED027A942910006A3A9 /* AFImageDownloader.m */,
457 + );
458 + path = "UIKit+AFNetworking";
459 + sourceTree = "<group>";
460 + };
461 + E6D8DED127A942910006A3A9 /* AFNetworking */ = {
462 + isa = PBXGroup;
463 + children = (
464 + E6D8DED227A942910006A3A9 /* AFSecurityPolicy.h */,
465 + E6D8DED327A942910006A3A9 /* AFNetworkReachabilityManager.h */,
466 + E6D8DED427A942910006A3A9 /* AFURLSessionManager.h */,
467 + E6D8DED527A942910006A3A9 /* AFURLRequestSerialization.h */,
468 + E6D8DED627A942910006A3A9 /* AFURLResponseSerialization.m */,
469 + E6D8DED727A942910006A3A9 /* AFHTTPSessionManager.m */,
470 + E6D8DED827A942910006A3A9 /* AFURLResponseSerialization.h */,
471 + E6D8DED927A942910006A3A9 /* AFURLSessionManager.m */,
472 + E6D8DEDA27A942910006A3A9 /* AFURLRequestSerialization.m */,
473 + E6D8DEDB27A942910006A3A9 /* AFNetworking.h */,
474 + E6D8DEDC27A942910006A3A9 /* AFNetworkReachabilityManager.m */,
475 + E6D8DEDD27A942910006A3A9 /* AFSecurityPolicy.m */,
476 + E6D8DEDE27A942910006A3A9 /* AFHTTPSessionManager.h */,
477 + );
478 + path = AFNetworking;
479 + sourceTree = "<group>";
480 + };
481 + E6D8DEDF27A942910006A3A9 /* fmdb */ = {
482 + isa = PBXGroup;
483 + children = (
484 + E6D8DEE027A942910006A3A9 /* FMDatabase.h */,
485 + E6D8DEE127A942910006A3A9 /* FMDatabaseQueue.m */,
486 + E6D8DEE227A942910006A3A9 /* FMResultSet.h */,
487 + E6D8DEE327A942910006A3A9 /* FMDatabasePool.h */,
488 + E6D8DEE427A942910006A3A9 /* FMDatabaseAdditions.m */,
489 + E6D8DEE527A942910006A3A9 /* FMDatabase.m */,
490 + E6D8DEE627A942910006A3A9 /* FMDatabaseQueue.h */,
491 + E6D8DEE727A942910006A3A9 /* FMDB.h */,
492 + E6D8DEE827A942910006A3A9 /* FMDatabaseAdditions.h */,
493 + E6D8DEE927A942910006A3A9 /* FMDatabasePool.m */,
494 + E6D8DEEA27A942910006A3A9 /* FMResultSet.m */,
495 + );
496 + path = fmdb;
497 + sourceTree = "<group>";
498 + };
499 +/* End PBXGroup section */
500 +
501 +/* Begin PBXHeadersBuildPhase section */
502 + E6D8DE6327A942010006A3A9 /* Headers */ = {
503 + isa = PBXHeadersBuildPhase;
504 + buildActionMask = 2147483647;
505 + files = (
506 + E6D8DEEF27A942920006A3A9 /* WarplyReactMethods.h in Headers */,
507 + E6D8DF0027A942920006A3A9 /* WLNativeAdsCollectionMode.h in Headers */,
508 + E6D8DF3027A942920006A3A9 /* AFImageDownloader.h in Headers */,
509 + E6D8DF4927A942920006A3A9 /* AFNetworking.h in Headers */,
510 + E6D8DF5827A942920006A3A9 /* WLEvent.h in Headers */,
511 + E6D8DF3927A942920006A3A9 /* UIRefreshControl+AFNetworking.h in Headers */,
512 + E6D8DF1A27A942920006A3A9 /* WLLocationManager.h in Headers */,
513 + E6D8DF2827A942920006A3A9 /* NSString+SSToolkitAdditions.h in Headers */,
514 + E6D8DF1627A942920006A3A9 /* WLUserManager.h in Headers */,
515 + E6D8DF2D27A942920006A3A9 /* UIButton+AFNetworking.h in Headers */,
516 + E6D8DF2A27A942920006A3A9 /* NSData+SSToolkitAdditions.h in Headers */,
517 + E6D8DF4027A942920006A3A9 /* AFSecurityPolicy.h in Headers */,
518 + E6D8DF3427A942920006A3A9 /* UIActivityIndicatorView+AFNetworking.h in Headers */,
519 + E6D8DF2F27A942920006A3A9 /* UIImageView+AFNetworking.h in Headers */,
520 + E6D8DF5927A942920006A3A9 /* Warply.h in Headers */,
521 + E6D8DF5327A942920006A3A9 /* FMDatabaseQueue.h in Headers */,
522 + E6D8DF1827A942920006A3A9 /* WLPushManager.h in Headers */,
523 + E6D8DF5427A942920006A3A9 /* FMDB.h in Headers */,
524 + E6D8DF0327A942920006A3A9 /* WLInboxItemViewController.h in Headers */,
525 + E6D8DEF627A942920006A3A9 /* WLCustomNativeAdTableViewCell.h in Headers */,
526 + E6D8DF4D27A942920006A3A9 /* FMDatabase.h in Headers */,
527 + E6D8DF0127A942920006A3A9 /* WLBeacon.h in Headers */,
528 + E6D8DF4C27A942920006A3A9 /* AFHTTPSessionManager.h in Headers */,
529 + E6D8DF1727A942920006A3A9 /* WLBeaconManager.h in Headers */,
530 + E6D8DF4127A942920006A3A9 /* AFNetworkReachabilityManager.h in Headers */,
531 + E6D8DF0527A942920006A3A9 /* WLAPSItem.h in Headers */,
532 + E6D8DF1D27A942920006A3A9 /* UIViewController+WLAdditions.h in Headers */,
533 + E6D8DEF227A942920006A3A9 /* WLNativeAdTableViewCell.h in Headers */,
534 + E6D8DF5527A942920006A3A9 /* FMDatabaseAdditions.h in Headers */,
535 + E6D8DF5027A942920006A3A9 /* FMDatabasePool.h in Headers */,
536 + E6D8DF2727A942920006A3A9 /* WLGlobals.h in Headers */,
537 + E6D8DF1F27A942920006A3A9 /* WLUtils.h in Headers */,
538 + E6D8DF0227A942920006A3A9 /* WLBaseItem.h in Headers */,
539 + E6D8DF3527A942920006A3A9 /* UIImage+AFNetworking.h in Headers */,
540 + E6D8DF3827A942920006A3A9 /* UIKit+AFNetworking.h in Headers */,
541 + E6D8DF4F27A942920006A3A9 /* FMResultSet.h in Headers */,
542 + E6D8DEFD27A942920006A3A9 /* WLNativeAdsTableMode.h in Headers */,
543 + E6D8DF2427A942920006A3A9 /* WLSMSActionHandlerDeprecated.h in Headers */,
544 + E6D8DF3627A942920006A3A9 /* UIProgressView+AFNetworking.h in Headers */,
545 + E6D8DEF027A942920006A3A9 /* WLNativeAdCollectionViewCell.h in Headers */,
546 + E6D8DF4327A942920006A3A9 /* AFURLRequestSerialization.h in Headers */,
547 + E6D8DF2227A942920006A3A9 /* WLSMSActionHanlder.h in Headers */,
548 + E6D8DF2627A942920006A3A9 /* WLAPPActionHandler.h in Headers */,
549 + E6D8DF4227A942920006A3A9 /* AFURLSessionManager.h in Headers */,
550 + E6D8DF1527A942920006A3A9 /* WLAnalyticsManager.h in Headers */,
551 + E6D8DF6227A9429E0006A3A9 /* MyApi.h in Headers */,
552 + E6D8DF3227A942920006A3A9 /* AFAutoPurgingImageCache.h in Headers */,
553 + E6D8DEFE27A942920006A3A9 /* WLCustomNativeCollectionViewCell.h in Headers */,
554 + E6D8DF0927A942920006A3A9 /* WLInboxItem.h in Headers */,
555 + E6D8DEFF27A942920006A3A9 /* WLNativeVideoTableViewCell.h in Headers */,
556 + E6D8DF3E27A942920006A3A9 /* AFNetworkActivityIndicatorManager.h in Headers */,
557 + E6D8DE6E27A942010006A3A9 /* WarplySDKFrameworkIOS.h in Headers */,
558 + E6D8DF3327A942920006A3A9 /* UIWebView+AFNetworking.h in Headers */,
559 + E6D8DF4627A942920006A3A9 /* AFURLResponseSerialization.h in Headers */,
560 + );
561 + runOnlyForDeploymentPostprocessing = 0;
562 + };
563 +/* End PBXHeadersBuildPhase section */
564 +
565 +/* Begin PBXNativeTarget section */
566 + E6D8DE6727A942010006A3A9 /* WarplySDKFrameworkIOS */ = {
567 + isa = PBXNativeTarget;
568 + buildConfigurationList = E6D8DE7127A942010006A3A9 /* Build configuration list for PBXNativeTarget "WarplySDKFrameworkIOS" */;
569 + buildPhases = (
570 + E6D8DE6327A942010006A3A9 /* Headers */,
571 + E6D8DE6427A942010006A3A9 /* Sources */,
572 + E6D8DE6527A942010006A3A9 /* Frameworks */,
573 + E6D8DE6627A942010006A3A9 /* Resources */,
574 + );
575 + buildRules = (
576 + );
577 + dependencies = (
578 + );
579 + name = WarplySDKFrameworkIOS;
580 + productName = WarplySDKFrameworkIOS;
581 + productReference = E6D8DE6827A942010006A3A9 /* WarplySDKFrameworkIOS.framework */;
582 + productType = "com.apple.product-type.framework";
583 + };
584 +/* End PBXNativeTarget section */
585 +
586 +/* Begin PBXProject section */
587 + E6D8DE5F27A942010006A3A9 /* Project object */ = {
588 + isa = PBXProject;
589 + attributes = {
590 + BuildIndependentTargetsInParallel = 1;
591 + LastUpgradeCheck = 1310;
592 + TargetAttributes = {
593 + E6D8DE6727A942010006A3A9 = {
594 + CreatedOnToolsVersion = 13.1;
595 + LastSwiftMigration = 1310;
596 + };
597 + };
598 + };
599 + buildConfigurationList = E6D8DE6227A942010006A3A9 /* Build configuration list for PBXProject "WarplySDKFrameworkIOS" */;
600 + compatibilityVersion = "Xcode 13.0";
601 + developmentRegion = en;
602 + hasScannedForEncodings = 0;
603 + knownRegions = (
604 + en,
605 + Base,
606 + );
607 + mainGroup = E6D8DE5E27A942000006A3A9;
608 + productRefGroup = E6D8DE6927A942010006A3A9 /* Products */;
609 + projectDirPath = "";
610 + projectRoot = "";
611 + targets = (
612 + E6D8DE6727A942010006A3A9 /* WarplySDKFrameworkIOS */,
613 + );
614 + };
615 +/* End PBXProject section */
616 +
617 +/* Begin PBXResourcesBuildPhase section */
618 + E6D8DE6627A942010006A3A9 /* Resources */ = {
619 + isa = PBXResourcesBuildPhase;
620 + buildActionMask = 2147483647;
621 + files = (
622 + E6D8DF5A27A942920006A3A9 /* Media.xcassets in Resources */,
623 + E6D8DF1127A942920006A3A9 /* warp_white_close_button.png in Resources */,
624 + E6D8DF0E27A942920006A3A9 /* warp_white_back_button.png in Resources */,
625 + E6D8DF0F27A942920006A3A9 /* warp_white_close_button@2x.png in Resources */,
626 + E6D8DF0D27A942920006A3A9 /* warp_white_forward_button.png in Resources */,
627 + E6D8DEFA27A942920006A3A9 /* WLNativeAdTableViewCell.xib in Resources */,
628 + E6D8DF1027A942920006A3A9 /* warp_white_forward_button@2x.png in Resources */,
629 + E6D8DEF127A942920006A3A9 /* WLNativeVideoTableViewCell.xib in Resources */,
630 + E6D8DEFB27A942920006A3A9 /* WLNativeAdCollectionViewCell.xib in Resources */,
631 + E6D8DF0C27A942920006A3A9 /* warp_white_back_button@2x.png in Resources */,
632 + );
633 + runOnlyForDeploymentPostprocessing = 0;
634 + };
635 +/* End PBXResourcesBuildPhase section */
636 +
637 +/* Begin PBXSourcesBuildPhase section */
638 + E6D8DE6427A942010006A3A9 /* Sources */ = {
639 + isa = PBXSourcesBuildPhase;
640 + buildActionMask = 2147483647;
641 + files = (
642 + E6D8DF0B27A942920006A3A9 /* WLEvent.m in Sources */,
643 + E6D8DF1E27A942920006A3A9 /* UIViewController+WLAdditions.m in Sources */,
644 + E6D8DF2E27A942920006A3A9 /* UIRefreshControl+AFNetworking.m in Sources */,
645 + E6D8DF4827A942920006A3A9 /* AFURLRequestSerialization.m in Sources */,
646 + E6D8DEF327A942920006A3A9 /* WLNativeVideoTableViewCell.m in Sources */,
647 + E6D8DF2527A942920006A3A9 /* WLSMSActionHanlder.m in Sources */,
648 + E6D8DF5727A942920006A3A9 /* FMResultSet.m in Sources */,
649 + E6D8DF3A27A942920006A3A9 /* UIButton+AFNetworking.m in Sources */,
650 + E6D8DF0627A942920006A3A9 /* WLBeacon.m in Sources */,
651 + E6D8DF2927A942920006A3A9 /* NSData+SSToolkitAdditions.m in Sources */,
652 + E6D8DEFC27A942920006A3A9 /* WLCustomNativeAdTableViewCell.m in Sources */,
653 + E6D8DF5F27A9429E0006A3A9 /* ProfileViewInterface.swift in Sources */,
654 + E6D8DF4A27A942920006A3A9 /* AFNetworkReachabilityManager.m in Sources */,
655 + E6D8DF4B27A942920006A3A9 /* AFSecurityPolicy.m in Sources */,
656 + E6D8DF1327A942920006A3A9 /* WLBeaconManager.m in Sources */,
657 + E6D8DF0427A942920006A3A9 /* WLInboxItem.m in Sources */,
658 + E6D8DF5127A942920006A3A9 /* FMDatabaseAdditions.m in Sources */,
659 + E6D8DF2127A942920006A3A9 /* WLAPPActionHandler.m in Sources */,
660 + E6D8DF5627A942920006A3A9 /* FMDatabasePool.m in Sources */,
661 + E6D8DF4527A942920006A3A9 /* AFHTTPSessionManager.m in Sources */,
662 + E6D8DF3B27A942920006A3A9 /* UIActivityIndicatorView+AFNetworking.m in Sources */,
663 + E6D8DF3727A942920006A3A9 /* UIImageView+AFNetworking.m in Sources */,
664 + E6D8DF3127A942920006A3A9 /* AFNetworkActivityIndicatorManager.m in Sources */,
665 + E6D8DF3D27A942920006A3A9 /* AFAutoPurgingImageCache.m in Sources */,
666 + E6D8DF0A27A942920006A3A9 /* WLAPSItem.m in Sources */,
667 + E6D8DF2C27A942920006A3A9 /* UIProgressView+AFNetworking.m in Sources */,
668 + E6D8DF3C27A942920006A3A9 /* UIWebView+AFNetworking.m in Sources */,
669 + E6D8DF1427A942920006A3A9 /* WLLocationManager.m in Sources */,
670 + E6D8DF6027A9429E0006A3A9 /* MyApi.m in Sources */,
671 + E6D8DF3F27A942920006A3A9 /* AFImageDownloader.m in Sources */,
672 + E6D8DEF727A942920006A3A9 /* WLNativeAdsCollectionMode.m in Sources */,
673 + E6D8DEF427A942920006A3A9 /* WLCustomNativeCollectionViewCell.m in Sources */,
674 + E6D8DF2B27A942920006A3A9 /* NSString+SSToolkitAdditions.m in Sources */,
675 + E6D8DF4727A942920006A3A9 /* AFURLSessionManager.m in Sources */,
676 + E6D8DF1927A942920006A3A9 /* WLAnalyticsManager.m in Sources */,
677 + E6D8DF5227A942920006A3A9 /* FMDatabase.m in Sources */,
678 + E6D8DF1227A942920006A3A9 /* WLPushManager.m in Sources */,
679 + E6D8DEF827A942920006A3A9 /* WLNativeAdTableViewCell.m in Sources */,
680 + E6D8DE6D27A942010006A3A9 /* WarplySDKFrameworkIOS.docc in Sources */,
681 + E6D8DF4427A942920006A3A9 /* AFURLResponseSerialization.m in Sources */,
682 + E6D8DEF527A942920006A3A9 /* WLNativeAdsTableMode.m in Sources */,
683 + E6D8DF1C27A942920006A3A9 /* WLUtils.m in Sources */,
684 + E6D8DF1B27A942920006A3A9 /* WLUserManager.m in Sources */,
685 + E6D8DF6127A9429E0006A3A9 /* ProfileView.swift in Sources */,
686 + E6D8DF2027A942920006A3A9 /* Warply.m in Sources */,
687 + E6D8DF2327A942920006A3A9 /* WLSMSActionHandlerDeprecated.m in Sources */,
688 + E6D8DEEE27A942920006A3A9 /* WarplyReactMethods.m in Sources */,
689 + E6D8DEF927A942920006A3A9 /* WLNativeAdCollectionViewCell.m in Sources */,
690 + E6D8DF4E27A942920006A3A9 /* FMDatabaseQueue.m in Sources */,
691 + E6D8DF0827A942920006A3A9 /* WLBaseItem.m in Sources */,
692 + E6D8DF0727A942920006A3A9 /* WLInboxItemViewController.m in Sources */,
693 + );
694 + runOnlyForDeploymentPostprocessing = 0;
695 + };
696 +/* End PBXSourcesBuildPhase section */
697 +
698 +/* Begin XCBuildConfiguration section */
699 + E6D8DE6F27A942010006A3A9 /* Debug */ = {
700 + isa = XCBuildConfiguration;
701 + buildSettings = {
702 + ALWAYS_SEARCH_USER_PATHS = NO;
703 + CLANG_ANALYZER_NONNULL = YES;
704 + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
705 + CLANG_CXX_LANGUAGE_STANDARD = "gnu++17";
706 + CLANG_CXX_LIBRARY = "libc++";
707 + CLANG_ENABLE_MODULES = YES;
708 + CLANG_ENABLE_OBJC_ARC = YES;
709 + CLANG_ENABLE_OBJC_WEAK = YES;
710 + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
711 + CLANG_WARN_BOOL_CONVERSION = YES;
712 + CLANG_WARN_COMMA = YES;
713 + CLANG_WARN_CONSTANT_CONVERSION = YES;
714 + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
715 + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
716 + CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
717 + CLANG_WARN_EMPTY_BODY = YES;
718 + CLANG_WARN_ENUM_CONVERSION = YES;
719 + CLANG_WARN_INFINITE_RECURSION = YES;
720 + CLANG_WARN_INT_CONVERSION = YES;
721 + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
722 + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
723 + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
724 + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
725 + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
726 + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
727 + CLANG_WARN_STRICT_PROTOTYPES = YES;
728 + CLANG_WARN_SUSPICIOUS_MOVE = YES;
729 + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
730 + CLANG_WARN_UNREACHABLE_CODE = YES;
731 + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
732 + COPY_PHASE_STRIP = NO;
733 + CURRENT_PROJECT_VERSION = 1;
734 + DEBUG_INFORMATION_FORMAT = dwarf;
735 + ENABLE_STRICT_OBJC_MSGSEND = YES;
736 + ENABLE_TESTABILITY = YES;
737 + GCC_C_LANGUAGE_STANDARD = gnu11;
738 + GCC_DYNAMIC_NO_PIC = NO;
739 + GCC_NO_COMMON_BLOCKS = YES;
740 + GCC_OPTIMIZATION_LEVEL = 0;
741 + GCC_PREPROCESSOR_DEFINITIONS = (
742 + "DEBUG=1",
743 + "$(inherited)",
744 + );
745 + GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
746 + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
747 + GCC_WARN_UNDECLARED_SELECTOR = YES;
748 + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
749 + GCC_WARN_UNUSED_FUNCTION = YES;
750 + GCC_WARN_UNUSED_VARIABLE = YES;
751 + IPHONEOS_DEPLOYMENT_TARGET = 15.0;
752 + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
753 + MTL_FAST_MATH = YES;
754 + ONLY_ACTIVE_ARCH = YES;
755 + SDKROOT = iphoneos;
756 + VERSIONING_SYSTEM = "apple-generic";
757 + VERSION_INFO_PREFIX = "";
758 + };
759 + name = Debug;
760 + };
761 + E6D8DE7027A942010006A3A9 /* Release */ = {
762 + isa = XCBuildConfiguration;
763 + buildSettings = {
764 + ALWAYS_SEARCH_USER_PATHS = NO;
765 + CLANG_ANALYZER_NONNULL = YES;
766 + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
767 + CLANG_CXX_LANGUAGE_STANDARD = "gnu++17";
768 + CLANG_CXX_LIBRARY = "libc++";
769 + CLANG_ENABLE_MODULES = YES;
770 + CLANG_ENABLE_OBJC_ARC = YES;
771 + CLANG_ENABLE_OBJC_WEAK = YES;
772 + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
773 + CLANG_WARN_BOOL_CONVERSION = YES;
774 + CLANG_WARN_COMMA = YES;
775 + CLANG_WARN_CONSTANT_CONVERSION = YES;
776 + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
777 + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
778 + CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
779 + CLANG_WARN_EMPTY_BODY = YES;
780 + CLANG_WARN_ENUM_CONVERSION = YES;
781 + CLANG_WARN_INFINITE_RECURSION = YES;
782 + CLANG_WARN_INT_CONVERSION = YES;
783 + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
784 + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
785 + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
786 + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
787 + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
788 + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
789 + CLANG_WARN_STRICT_PROTOTYPES = YES;
790 + CLANG_WARN_SUSPICIOUS_MOVE = YES;
791 + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
792 + CLANG_WARN_UNREACHABLE_CODE = YES;
793 + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
794 + COPY_PHASE_STRIP = NO;
795 + CURRENT_PROJECT_VERSION = 1;
796 + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
797 + ENABLE_NS_ASSERTIONS = NO;
798 + ENABLE_STRICT_OBJC_MSGSEND = YES;
799 + GCC_C_LANGUAGE_STANDARD = gnu11;
800 + GCC_NO_COMMON_BLOCKS = YES;
801 + GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
802 + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
803 + GCC_WARN_UNDECLARED_SELECTOR = YES;
804 + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
805 + GCC_WARN_UNUSED_FUNCTION = YES;
806 + GCC_WARN_UNUSED_VARIABLE = YES;
807 + IPHONEOS_DEPLOYMENT_TARGET = 15.0;
808 + MTL_ENABLE_DEBUG_INFO = NO;
809 + MTL_FAST_MATH = YES;
810 + SDKROOT = iphoneos;
811 + VALIDATE_PRODUCT = YES;
812 + VERSIONING_SYSTEM = "apple-generic";
813 + VERSION_INFO_PREFIX = "";
814 + };
815 + name = Release;
816 + };
817 + E6D8DE7227A942010006A3A9 /* Debug */ = {
818 + isa = XCBuildConfiguration;
819 + buildSettings = {
820 + CLANG_ENABLE_MODULES = YES;
821 + CODE_SIGN_STYLE = Automatic;
822 + CURRENT_PROJECT_VERSION = 1;
823 + DEFINES_MODULE = YES;
824 + DEVELOPMENT_TEAM = VW5AF53FLP;
825 + DYLIB_COMPATIBILITY_VERSION = 1;
826 + DYLIB_CURRENT_VERSION = 1;
827 + DYLIB_INSTALL_NAME_BASE = "@rpath";
828 + GENERATE_INFOPLIST_FILE = YES;
829 + INFOPLIST_KEY_NSHumanReadableCopyright = "";
830 + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
831 + IPHONEOS_DEPLOYMENT_TARGET = 13.0;
832 + LD_RUNPATH_SEARCH_PATHS = (
833 + "$(inherited)",
834 + "@executable_path/Frameworks",
835 + "@loader_path/Frameworks",
836 + );
837 + MARKETING_VERSION = 1.0;
838 + PRODUCT_BUNDLE_IDENTIFIER = framework.warp.ly.WarplySDKFrameworkIOS;
839 + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)";
840 + SKIP_INSTALL = YES;
841 + SUPPORTS_MACCATALYST = NO;
842 + SWIFT_EMIT_LOC_STRINGS = YES;
843 + SWIFT_OPTIMIZATION_LEVEL = "-Onone";
844 + SWIFT_VERSION = 5.0;
845 + TARGETED_DEVICE_FAMILY = "1,2";
846 + };
847 + name = Debug;
848 + };
849 + E6D8DE7327A942010006A3A9 /* Release */ = {
850 + isa = XCBuildConfiguration;
851 + buildSettings = {
852 + CLANG_ENABLE_MODULES = YES;
853 + CODE_SIGN_STYLE = Automatic;
854 + CURRENT_PROJECT_VERSION = 1;
855 + DEFINES_MODULE = YES;
856 + DEVELOPMENT_TEAM = VW5AF53FLP;
857 + DYLIB_COMPATIBILITY_VERSION = 1;
858 + DYLIB_CURRENT_VERSION = 1;
859 + DYLIB_INSTALL_NAME_BASE = "@rpath";
860 + GENERATE_INFOPLIST_FILE = YES;
861 + INFOPLIST_KEY_NSHumanReadableCopyright = "";
862 + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
863 + IPHONEOS_DEPLOYMENT_TARGET = 13.0;
864 + LD_RUNPATH_SEARCH_PATHS = (
865 + "$(inherited)",
866 + "@executable_path/Frameworks",
867 + "@loader_path/Frameworks",
868 + );
869 + MARKETING_VERSION = 1.0;
870 + PRODUCT_BUNDLE_IDENTIFIER = framework.warp.ly.WarplySDKFrameworkIOS;
871 + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)";
872 + SKIP_INSTALL = YES;
873 + SUPPORTS_MACCATALYST = NO;
874 + SWIFT_EMIT_LOC_STRINGS = YES;
875 + SWIFT_VERSION = 5.0;
876 + TARGETED_DEVICE_FAMILY = "1,2";
877 + };
878 + name = Release;
879 + };
880 +/* End XCBuildConfiguration section */
881 +
882 +/* Begin XCConfigurationList section */
883 + E6D8DE6227A942010006A3A9 /* Build configuration list for PBXProject "WarplySDKFrameworkIOS" */ = {
884 + isa = XCConfigurationList;
885 + buildConfigurations = (
886 + E6D8DE6F27A942010006A3A9 /* Debug */,
887 + E6D8DE7027A942010006A3A9 /* Release */,
888 + );
889 + defaultConfigurationIsVisible = 0;
890 + defaultConfigurationName = Release;
891 + };
892 + E6D8DE7127A942010006A3A9 /* Build configuration list for PBXNativeTarget "WarplySDKFrameworkIOS" */ = {
893 + isa = XCConfigurationList;
894 + buildConfigurations = (
895 + E6D8DE7227A942010006A3A9 /* Debug */,
896 + E6D8DE7327A942010006A3A9 /* Release */,
897 + );
898 + defaultConfigurationIsVisible = 0;
899 + defaultConfigurationName = Release;
900 + };
901 +/* End XCConfigurationList section */
902 + };
903 + rootObject = E6D8DE5F27A942010006A3A9 /* Project object */;
904 +}
1 +<?xml version="1.0" encoding="UTF-8"?>
2 +<Workspace
3 + version = "1.0">
4 + <FileRef
5 + location = "self:">
6 + </FileRef>
7 +</Workspace>
1 +<?xml version="1.0" encoding="UTF-8"?>
2 +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3 +<plist version="1.0">
4 +<dict>
5 + <key>IDEDidComputeMac32BitWarning</key>
6 + <true/>
7 +</dict>
8 +</plist>
1 +<?xml version="1.0" encoding="UTF-8"?>
2 +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3 +<plist version="1.0">
4 +<dict>
5 + <key>SchemeUserState</key>
6 + <dict>
7 + <key>WarplySDKFrameworkIOS.xcscheme_^#shared#^_</key>
8 + <dict>
9 + <key>orderHint</key>
10 + <integer>0</integer>
11 + </dict>
12 + </dict>
13 +</dict>
14 +</plist>
1 +//
2 +// MyApi.h
3 +// warplyFramework
4 +//
5 +// Created by Βασιλης Σκουρας on 8/12/21.
6 +//
7 +
8 +#ifndef MyApi_h
9 +#define MyApi_h
10 +#import <UIKit/UIKit.h>
11 +
12 +@interface MyApi : NSObject
13 +
14 ++ (void)init:(NSDictionary *)launchOptions uuid:(NSString*)uuid merchantId:(NSString*)merchantId lang:(NSString*)lang;
15 +- (void) setToStage;
16 +- (UIViewController *) openProfile:(UIViewController*)controller :(UIWindow*) window;
17 +- (void) applicationDidEnterBackground:(UIApplication *)application;
18 +- (void) applicationWillEnterForeground:(UIApplication *)application;
19 +- (void) applicationDidBecomeActive:(UIApplication *)application;
20 +- (void) applicationWillTerminate:(UIApplication *)application;
21 +- (void) application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken;
22 +- (void) application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error;
23 +- (void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo;
24 +- (NSMutableArray *)getProducts:(NSString *) filter;
25 +- (NSMutableArray*)sendContact:(NSString*)name email:(NSString*)email msisdn:(NSString*)msisdn message:(NSString*)message;
26 +- (NSMutableArray *)getContent:(NSString *)category tags:(NSArray *)tags;
27 +- (NSMutableArray *)getMerchantCategories;
28 +- (NSMutableArray *)getMerchants;
29 +- (NSMutableArray *)getTagsCategories;
30 +- (NSMutableArray *)getTags;
31 +- (NSDictionary *)login:(NSString *)id password:(NSString *)password loginType:(NSString*) loginType;
32 +- (NSDictionary *)register:(NSString *)id password:(NSString *)password name:(NSString*)name email:(NSString*)email segmentation:(NSNumber*)segmentation newsletter:(NSNumber*)newsletter;
33 +- (NSDictionary *)registerAutoLogin:(NSString *)id password:(NSString *)password name:(NSString*)name email:(NSString*)email segmentation:(NSNumber*)segmentation newsletter:(NSNumber*)newsletter loginType:(NSString*)loginType;
34 +- (NSDictionary *)refreshToken;
35 +- (NSDictionary *)changePassword:(NSString *)oldPassword newPassword:(NSString *)newPassword;
36 +- (NSDictionary *)getProfile;
37 +- (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;
38 +- (NSDictionary *)changeProfileImage:(NSString*)image andUserId:(NSString*)userId;
39 +- (NSDictionary*) addCard:(NSString*)number andCardIssuer:(NSString*)cardIssuer andCardHolder:(NSString*)cardHolder andExpirationMonth:(NSString*)expirationMonth andExpirationYear:(NSString*)expirationYear;
40 +- (NSDictionary*) getCards;
41 +- (NSDictionary*) deleteCard:(NSString*)token;
42 +- (NSDictionary*) verifyTicket:(NSString*)guid ticket:(NSString*)ticket;
43 +- (NSDictionary*) getCoupons;
44 +- (NSDictionary*) getTransactionHistory;
45 +- (NSDictionary*) getPointsHistory;
46 +- (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;
47 +- (NSDictionary*)getAddress;
48 +- (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;
49 +- (NSDictionary*)deleteAddress:(NSString*)uuid;
50 +- (NSDictionary*)redeemCoupon:(NSString*)id andUuid:(NSString*)uuid;
51 +- (NSDictionary*)forgotPasswordWithId:(NSString*)id andConfCode:(NSString*)confCode andOtpUuid:(NSString*)otpUuid;
52 +- (NSDictionary*)resetPasswordWithPassword:(NSString*)password andConfCode:(NSString*)confCode andOtpUuid:(NSString*)otpUuid andConfToken:(NSString*)confToken;
53 +- (NSDictionary*)requestOtpWithMsisdn:(NSString*)msisdn andScope:(NSString*)scope;
54 +- (NSDictionary*)retrieveMultilingualMerchantsWithCategories:(NSArray*)categories andDefaultShown:(NSNumber*)defaultShown andCenter:(NSNumber*)center andTags:(NSArray*)tags andUuid:(NSString*)uuid andDistance:(NSNumber*)distance;
55 +
56 +@end
57 +#endif /* MyApi_h */
1 +//
2 +// MyApi.m
3 +// warplyFramework
4 +//
5 +// Created by Βασιλης Σκουρας on 8/12/21.
6 +//
7 +
8 +#import <Foundation/Foundation.h>
9 +#import "MyApi.h"
10 +#import "Warply.h"
11 +
12 +#import <warplySDKFrameworkIOS/warplySDKFrameworkIOS-Swift.h>
13 +
14 +@implementation MyApi
15 +NSString *WARP_PRODUCTION_BASE_URL = @"https://engage.warp.ly";
16 +NSString *WARP_HOST = @"engage.warp.ly";
17 +NSString *WARP_ERROR_DOMAIN = @"engage.warp.ly";
18 +NSString *MERCHANT_ID;
19 +NSString *LANG;
20 +
21 ++ (void)init:(NSDictionary *)launchOptions uuid:(NSString*)uuid merchantId:(NSString*)merchantId lang:(NSString*)lang{
22 + #if (DEBUG == 1)
23 + [Warply launchWithAppUUID:uuid launchOptions:launchOptions];
24 + #else
25 + [Warply launchWithAppUUID:uuid launchOptions:launchOptions];
26 + #endif
27 + [[Warply sharedService].pushManager registerForRemoteNotifications];
28 + [[Warply sharedService].pushManager resetBadge];
29 + MERCHANT_ID = merchantId;
30 + LANG = lang;
31 +}
32 +
33 +- (void) setToStage {
34 + WARP_PRODUCTION_BASE_URL = @"https://engage-stage.warp.ly";
35 + WARP_HOST = @"engage-stage.warp.ly";
36 + WARP_ERROR_DOMAIN = @"engage-stage.warp.ly";
37 +}
38 +
39 +- (UIViewController *) openProfile:(UIViewController*)controller :(UIWindow*) window {
40 +
41 + UIViewController *profileViewController = [ProfileViewInterface profileViewController];
42 +// controller = [[UINavigationController alloc]initWithRootViewController:profileViewController];
43 +
44 +// [window makeKeyAndVisible];
45 + return profileViewController;
46 +}
47 +
48 +///////////////////////////////////////////////////////////////////////////////////////////////////
49 +- (void)applicationDidEnterBackground:(UIApplication *)application
50 +{
51 +
52 + [[Warply sharedService] applicationDidEnterBackground];
53 +}
54 +
55 +///////////////////////////////////////////////////////////////////////////////////////////////////
56 +- (void)applicationWillEnterForeground:(UIApplication *)application
57 +{
58 + [[Warply sharedService] applicationWillEnterForeground];
59 +}
60 +
61 +
62 +- (void)applicationDidBecomeActive:(UIApplication *)application
63 +{
64 + [[Warply sharedService] applicationDidBecomeActive];
65 + [[Warply sharedService].pushManager resetBadge];
66 +}
67 +
68 +///////////////////////////////////////////////////////////////////////////////////////////////////
69 +- (void)applicationWillTerminate:(UIApplication *)application
70 +{
71 + [[Warply sharedService] applicationWillTerminate];
72 +}
73 +
74 +//#pragma mark - UIApplicationDelegate/RemoteNotificationsRegistration
75 +///////////////////////////////////////////////////////////////////////////////////////////////////
76 +- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
77 +{
78 + [[Warply sharedService].pushManager didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
79 +}
80 +
81 +///////////////////////////////////////////////////////////////////////////////////////////////////
82 +- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
83 +{
84 + [[Warply sharedService].pushManager didFailToRegisterForRemoteNotificationsWithError:error];
85 +}
86 +
87 +//#pragma mark - UIApplicationDelegate/Notifications
88 +///////////////////////////////////////////////////////////////////////////////////////////////////
89 +- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
90 +{
91 + [[Warply sharedService].pushManager application:application didReceiveRemoteNotification:userInfo];
92 + [[Warply sharedService].pushManager resetBadge];
93 +}
94 +
95 +- (NSMutableArray *)getProducts:(NSString *) filter {
96 + __block NSMutableArray *prods = [NSMutableArray alloc];
97 + __block BOOL isRunLoopNested = NO;
98 + __block BOOL isOperationCompleted = NO;
99 + [[Warply sharedService] getProductsWithSuccessBlock:filter :^(NSMutableArray *products) {
100 + prods = products;
101 + isOperationCompleted = YES;
102 + if (isRunLoopNested) {
103 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
104 + }
105 + } failureBlock:^(NSError *error) {
106 + NSLog(@"%@", error);
107 + prods = nil;
108 + isOperationCompleted = YES;
109 + if (isRunLoopNested) {
110 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
111 + }
112 + }];
113 + if ( ! isOperationCompleted) {
114 + isRunLoopNested = YES;
115 + NSLog(@"Waiting...");
116 + CFRunLoopRun(); // Magic!
117 + isRunLoopNested = NO;
118 + }
119 + return prods;
120 +}
121 +
122 +-(NSMutableArray*)sendContact:(NSString*)name email:(NSString*)email msisdn:(NSString*)msisdn message:(NSString*)message{
123 + __block NSMutableArray *resp = [NSMutableArray alloc];
124 + __block BOOL isRunLoopNested = NO;
125 + __block BOOL isOperationCompleted = NO;
126 + [[Warply sharedService] sendContactWithSuccessBlock:name andEmail:email andMsisdn:msisdn andMessage:message :^(NSMutableArray *response) {
127 + resp = response;
128 + isOperationCompleted = YES;
129 + if (isRunLoopNested) {
130 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
131 + }
132 + } failureBlock:^(NSError *error) {
133 + NSLog(@"%@", error);
134 + resp = nil;
135 + isOperationCompleted = YES;
136 + if (isRunLoopNested) {
137 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
138 + }
139 + }];
140 + if ( ! isOperationCompleted) {
141 + isRunLoopNested = YES;
142 + NSLog(@"Waiting...");
143 + CFRunLoopRun(); // Magic!
144 + isRunLoopNested = NO;
145 + }
146 + return resp;
147 +}
148 +
149 +- (NSMutableArray *)getContentWithCategory:(NSString *)category tags:(NSArray *)tags {
150 + __block NSMutableArray *cont = [NSMutableArray alloc];
151 + __block BOOL isRunLoopNested = NO;
152 + __block BOOL isOperationCompleted = NO;
153 + [[Warply sharedService] getContentWithCategoryWithSuccessBlock:category andTags:tags :^(NSMutableArray *content) {
154 + cont = content;
155 + isOperationCompleted = YES;
156 + if (isRunLoopNested) {
157 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
158 + }
159 + } failureBlock:^(NSError *error) {
160 + NSLog(@"%@", error);
161 + cont = nil;
162 + isOperationCompleted = YES;
163 + if (isRunLoopNested) {
164 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
165 + }
166 + }];
167 + if ( ! isOperationCompleted) {
168 + isRunLoopNested = YES;
169 + NSLog(@"Waiting...");
170 + CFRunLoopRun(); // Magic!
171 + isRunLoopNested = NO;
172 + }
173 + return cont;
174 +}
175 +
176 +- (NSMutableArray *)getMerchantCategories {
177 + __block NSMutableArray *cats = [NSMutableArray alloc];
178 + __block BOOL isRunLoopNested = NO;
179 + __block BOOL isOperationCompleted = NO;
180 + [[Warply sharedService] getMerchantCategoriesWithSuccessBlock :^(NSMutableArray *categories) {
181 + cats = categories;
182 + isOperationCompleted = YES;
183 + if (isRunLoopNested) {
184 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
185 + }
186 + } failureBlock:^(NSError *error) {
187 + NSLog(@"%@", error);
188 + cats = nil;
189 + isOperationCompleted = YES;
190 + if (isRunLoopNested) {
191 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
192 + }
193 + }];
194 + if ( ! isOperationCompleted) {
195 + isRunLoopNested = YES;
196 + NSLog(@"Waiting...");
197 + CFRunLoopRun(); // Magic!
198 + isRunLoopNested = NO;
199 + }
200 + return cats;
201 +}
202 +
203 +- (NSMutableArray *)getMerchants {
204 + __block NSMutableArray *mers = [NSMutableArray alloc];
205 + __block BOOL isRunLoopNested = NO;
206 + __block BOOL isOperationCompleted = NO;
207 + [[Warply sharedService] getMerchantsWithSuccessBlock:^(NSMutableArray *merchants) {
208 + mers = merchants;
209 + isOperationCompleted = YES;
210 + if (isRunLoopNested) {
211 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
212 + }
213 + } failureBlock:^(NSError *error) {
214 + NSLog(@"%@", error);
215 + mers = nil;
216 + isOperationCompleted = YES;
217 + if (isRunLoopNested) {
218 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
219 + }
220 + }];
221 + if ( ! isOperationCompleted) {
222 + isRunLoopNested = YES;
223 + NSLog(@"Waiting...");
224 + CFRunLoopRun(); // Magic!
225 + isRunLoopNested = NO;
226 + }
227 + return mers;
228 +}
229 +
230 +- (NSMutableArray *)getTagsCategories {
231 + __block NSMutableArray *categories = [NSMutableArray alloc];
232 + __block BOOL isRunLoopNested = NO;
233 + __block BOOL isOperationCompleted = NO;
234 + [[Warply sharedService] getTagsCategoriesWithSuccessBlock :^(NSMutableArray *tagsCategories) {
235 + categories = tagsCategories;
236 + isOperationCompleted = YES;
237 + if (isRunLoopNested) {
238 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
239 + }
240 + } failureBlock:^(NSError *error) {
241 + NSLog(@"%@", error);
242 + categories = nil;
243 + isOperationCompleted = YES;
244 + if (isRunLoopNested) {
245 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
246 + }
247 + }];
248 + if ( ! isOperationCompleted) {
249 + isRunLoopNested = YES;
250 + NSLog(@"Waiting...");
251 + CFRunLoopRun(); // Magic!
252 + isRunLoopNested = NO;
253 + }
254 + return categories;
255 +}
256 +
257 +- (NSMutableArray *)getTags {
258 + __block NSMutableArray *tgs = [NSMutableArray alloc];
259 + __block BOOL isRunLoopNested = NO;
260 + __block BOOL isOperationCompleted = NO;
261 + [[Warply sharedService] getTagsWithSuccessBlock :^(NSMutableArray *tags) {
262 + tgs = tags;
263 + isOperationCompleted = YES;
264 + if (isRunLoopNested) {
265 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
266 + }
267 + } failureBlock:^(NSError *error) {
268 + NSLog(@"%@", error);
269 + tgs = nil;
270 + isOperationCompleted = YES;
271 + if (isRunLoopNested) {
272 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
273 + }
274 + }];
275 + if ( ! isOperationCompleted) {
276 + isRunLoopNested = YES;
277 + NSLog(@"Waiting...");
278 + CFRunLoopRun(); // Magic!
279 + isRunLoopNested = NO;
280 + }
281 + return tgs;
282 +}
283 +
284 +- (NSDictionary *)login:(NSString *)id password:(NSString *)password loginType:(NSString*) loginType{
285 + __block NSDictionary *resp = [NSDictionary alloc];
286 + __block BOOL isRunLoopNested = NO;
287 + __block BOOL isOperationCompleted = NO;
288 + [[Warply sharedService] loginWithSuccessBlock:id andPassword:password andLoginType:loginType:^(NSDictionary *response) {
289 + if ([[response objectForKey:@"status"] isEqual:@1]) {
290 + NSString* clientId = [NSString alloc];
291 + clientId = [response objectForKey:@"client_id"];
292 + NSString* clientSecret = [NSString alloc];
293 + clientSecret = [response objectForKey:@"client_secret"];
294 + [[Warply sharedService] webAuthorizeWithSuccessBlock:response andId:id andLoginType:loginType :^(NSDictionary *response) {
295 + [[Warply sharedService] tokenWithSuccessBlock:response andClientId:clientId andClientSecret:clientSecret andLoginType:loginType :^(NSDictionary *response) {
296 + resp = response;
297 + isOperationCompleted = YES;
298 + if (isRunLoopNested) {
299 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
300 + }
301 + } failureBlock:^(NSError *error) {
302 + NSLog(@"%@", error);
303 + resp = nil;
304 + isOperationCompleted = YES;
305 + if (isRunLoopNested) {
306 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
307 + }
308 + }];
309 + } failureBlock:^(NSError *error){
310 + NSLog(@"%@", error);
311 + resp = nil;
312 + isOperationCompleted = YES;
313 + if (isRunLoopNested) {
314 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
315 + }
316 + }];
317 + } else {
318 + resp = response;
319 + isOperationCompleted = YES;
320 + if (isRunLoopNested) {
321 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
322 + }
323 + }
324 + } failureBlock:^(NSError *error) {
325 + NSLog(@"%@", error);
326 + resp = nil;
327 + isOperationCompleted = YES;
328 + if (isRunLoopNested) {
329 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
330 + }
331 + }];
332 + if ( ! isOperationCompleted) {
333 + isRunLoopNested = YES;
334 + NSLog(@"Waiting...");
335 + CFRunLoopRun(); // Magic!
336 + isRunLoopNested = NO;
337 + }
338 + return resp;
339 +}
340 +
341 +- (NSDictionary *)register:(NSString *)id password:(NSString *)password name:(NSString*)name email:(NSString*)email segmentation:(NSNumber*)segmentation newsletter:(NSNumber*)newsletter {
342 + __block NSDictionary *resp = [NSDictionary alloc];
343 + __block BOOL isRunLoopNested = NO;
344 + __block BOOL isOperationCompleted = NO;
345 + [[Warply sharedService] registerWithSuccessBlock:id andPassword:password andName:(NSString*)name andEmail:(NSString*)email andSegmentation:(NSNumber*)segmentation andNewsletter:(NSNumber*)newsletter :^(NSDictionary *response) {
346 + resp = response;
347 + isOperationCompleted = YES;
348 + if (isRunLoopNested) {
349 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
350 + }
351 + } failureBlock:^(NSError *error) {
352 + NSLog(@"%@", error);
353 + resp = nil;
354 + isOperationCompleted = YES;
355 + if (isRunLoopNested) {
356 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
357 + }
358 + }];
359 + if ( ! isOperationCompleted) {
360 + isRunLoopNested = YES;
361 + NSLog(@"Waiting...");
362 + CFRunLoopRun(); // Magic!
363 + isRunLoopNested = NO;
364 + }
365 + return resp;
366 +}
367 +
368 +- (NSDictionary *)registerAutoLogin:(NSString *)id password:(NSString *)password name:(NSString*)name email:(NSString*)email segmentation:(NSNumber*)segmentation newsletter:(NSNumber*)newsletter loginType:(NSString*)loginType {
369 + __block NSDictionary *resp = [NSDictionary alloc];
370 + __block BOOL isRunLoopNested = NO;
371 + __block BOOL isOperationCompleted = NO;
372 + [[Warply sharedService] registerWithSuccessBlock:id andPassword:password andName:(NSString*)name andEmail:(NSString*)email andSegmentation:(NSNumber*)segmentation andNewsletter:(NSNumber*)newsletter :^(NSDictionary *response) {
373 +
374 + if ([[response objectForKey:@"status"] isEqual:@1]) {
375 + [[Warply sharedService] loginWithSuccessBlock:id andPassword:password andLoginType:loginType:^(NSDictionary *response) {
376 + NSString* clientId = [NSString alloc];
377 + clientId = [response objectForKey:@"client_id"];
378 + NSString* clientSecret = [NSString alloc];
379 + clientSecret = [response objectForKey:@"client_secret"];
380 + [[Warply sharedService] webAuthorizeWithSuccessBlock:response andId:id andLoginType:loginType :^(NSDictionary *response) {
381 + [[Warply sharedService] tokenWithSuccessBlock:response andClientId:clientId andClientSecret:clientSecret andLoginType:loginType :^(NSDictionary *response) {
382 + resp = response;
383 + isOperationCompleted = YES;
384 + if (isRunLoopNested) {
385 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
386 + }
387 + } failureBlock:^(NSError *error) {
388 + NSLog(@"%@", error);
389 + resp = nil;
390 + isOperationCompleted = YES;
391 + if (isRunLoopNested) {
392 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
393 + }
394 + }];
395 + } failureBlock:^(NSError *error){
396 + NSLog(@"%@", error);
397 + resp = nil;
398 + isOperationCompleted = YES;
399 + if (isRunLoopNested) {
400 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
401 + }
402 + }];
403 + } failureBlock:^(NSError *error) {
404 + NSLog(@"%@", error);
405 + resp = nil;
406 + isOperationCompleted = YES;
407 + if (isRunLoopNested) {
408 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
409 + }
410 + }];
411 + }
412 + } failureBlock:^(NSError *error) {
413 + NSLog(@"%@", error);
414 + resp = nil;
415 + isOperationCompleted = YES;
416 + if (isRunLoopNested) {
417 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
418 + }
419 + }];
420 + if ( ! isOperationCompleted) {
421 + isRunLoopNested = YES;
422 + NSLog(@"Waiting...");
423 + CFRunLoopRun(); // Magic!
424 + isRunLoopNested = NO;
425 + }
426 + return resp;
427 +}
428 +
429 +- (NSDictionary *)refreshToken {
430 + __block NSDictionary *resp = [NSDictionary alloc];
431 + __block BOOL isRunLoopNested = NO;
432 + __block BOOL isOperationCompleted = NO;
433 + [[Warply sharedService] refreshToken:^(NSDictionary *response) {
434 + resp = response;
435 + isOperationCompleted = YES;
436 + if (isRunLoopNested) {
437 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
438 + }
439 + } failureBlock:^(NSError *error) {
440 + NSLog(@"%@", error);
441 + resp = nil;
442 + isOperationCompleted = YES;
443 + if (isRunLoopNested) {
444 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
445 + }
446 + }];
447 + if ( ! isOperationCompleted) {
448 + isRunLoopNested = YES;
449 + NSLog(@"Waiting...");
450 + CFRunLoopRun(); // Magic!
451 + isRunLoopNested = NO;
452 + }
453 + return resp;
454 +}
455 +
456 +- (NSDictionary *)changePassword:(NSString *)oldPassword newPassword:(NSString *)newPassword {
457 + __block NSDictionary *resp = [NSDictionary alloc];
458 + __block BOOL isRunLoopNested = NO;
459 + __block BOOL isOperationCompleted = NO;
460 + [[Warply sharedService] changePasswordWithSuccessBlock:oldPassword andNewPassword:newPassword :^(NSDictionary *response) {
461 + resp = response;
462 + isOperationCompleted = YES;
463 + if (isRunLoopNested) {
464 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
465 + }
466 + } failureBlock:^(NSError *error) {
467 + NSLog(@"%@", error);
468 + resp = nil;
469 + isOperationCompleted = YES;
470 + if (isRunLoopNested) {
471 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
472 + }
473 + }];
474 + if ( ! isOperationCompleted) {
475 + isRunLoopNested = YES;
476 + NSLog(@"Waiting...");
477 + CFRunLoopRun(); // Magic!
478 + isRunLoopNested = NO;
479 + }
480 + return resp;
481 +}
482 +
483 +- (NSDictionary *)getProfile {
484 + __block NSDictionary *resp = [NSDictionary alloc];
485 + __block BOOL isRunLoopNested = NO;
486 + __block BOOL isOperationCompleted = NO;
487 + [[Warply sharedService] getProfileWithSuccessBlock:^(NSDictionary *response) {
488 + resp = response;
489 + isOperationCompleted = YES;
490 + if (isRunLoopNested) {
491 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
492 + }
493 + } failureBlock:^(NSError *error) {
494 + NSLog(@"%@", error);
495 + resp = nil;
496 + isOperationCompleted = YES;
497 + if (isRunLoopNested) {
498 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
499 + }
500 + }];
501 + if ( ! isOperationCompleted) {
502 + isRunLoopNested = YES;
503 + NSLog(@"Waiting...");
504 + CFRunLoopRun(); // Magic!
505 + isRunLoopNested = NO;
506 + }
507 + return resp;
508 +}
509 +
510 +- (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{
511 + __block NSDictionary *resp = [NSDictionary alloc];
512 + __block BOOL isRunLoopNested = NO;
513 + __block BOOL isOperationCompleted = NO;
514 + [[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) {
515 + resp = response;
516 + isOperationCompleted = YES;
517 + if (isRunLoopNested) {
518 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
519 + }
520 + } failureBlock:^(NSError *error) {
521 + NSLog(@"%@", error);
522 + resp = nil;
523 + isOperationCompleted = YES;
524 + if (isRunLoopNested) {
525 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
526 + }
527 + }];
528 + if ( ! isOperationCompleted) {
529 + isRunLoopNested = YES;
530 + NSLog(@"Waiting...");
531 + CFRunLoopRun(); // Magic!
532 + isRunLoopNested = NO;
533 + }
534 + return resp;
535 +}
536 +
537 +- (NSDictionary *)changeProfileImage:(NSString*)image andUserId:(NSString*)userId {
538 + __block NSDictionary *resp = [NSDictionary alloc];
539 + __block BOOL isRunLoopNested = NO;
540 + __block BOOL isOperationCompleted = NO;
541 + [[Warply sharedService] changeProfileImageWithSuccessBlock:image andUserId:userId :^(NSDictionary *response) {
542 + resp = response;
543 + isOperationCompleted = YES;
544 + if (isRunLoopNested) {
545 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
546 + }
547 + } failureBlock:^(NSError *error) {
548 + NSLog(@"%@", error);
549 + resp = nil;
550 + isOperationCompleted = YES;
551 + if (isRunLoopNested) {
552 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
553 + }
554 + }];
555 + if ( ! isOperationCompleted) {
556 + isRunLoopNested = YES;
557 + NSLog(@"Waiting...");
558 + CFRunLoopRun(); // Magic!
559 + isRunLoopNested = NO;
560 + }
561 + return resp;
562 +}
563 +
564 +- (NSDictionary*) addCard:(NSString*)number andCardIssuer:(NSString*)cardIssuer andCardHolder:(NSString*)cardHolder andExpirationMonth:(NSString*)expirationMonth andExpirationYear:(NSString*)expirationYear {
565 + __block NSDictionary *resp = [NSDictionary alloc];
566 + __block BOOL isRunLoopNested = NO;
567 + __block BOOL isOperationCompleted = NO;
568 + [[Warply sharedService] addCardWithSuccessBlock:number andCardIssuer:cardIssuer andCardHolder:cardHolder andExpirationMonth:expirationMonth andExpirationYear:expirationYear :^(NSDictionary *response) {
569 + resp = response;
570 + isOperationCompleted = YES;
571 + if (isRunLoopNested) {
572 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
573 + }
574 + } failureBlock:^(NSError *error) {
575 + NSLog(@"%@", error);
576 + resp = nil;
577 + isOperationCompleted = YES;
578 + if (isRunLoopNested) {
579 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
580 + }
581 + }];
582 + if ( ! isOperationCompleted) {
583 + isRunLoopNested = YES;
584 + NSLog(@"Waiting...");
585 + CFRunLoopRun(); // Magic!
586 + isRunLoopNested = NO;
587 + }
588 + return resp;
589 +}
590 +
591 +- (NSDictionary*) getCards {
592 + __block NSDictionary *resp = [NSDictionary alloc];
593 + __block BOOL isRunLoopNested = NO;
594 + __block BOOL isOperationCompleted = NO;
595 + [[Warply sharedService] getCardsWithSuccessBlock:^(NSDictionary *response) {
596 + resp = response;
597 + isOperationCompleted = YES;
598 + if (isRunLoopNested) {
599 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
600 + }
601 + } failureBlock:^(NSError *error) {
602 + NSLog(@"%@", error);
603 + resp = nil;
604 + isOperationCompleted = YES;
605 + if (isRunLoopNested) {
606 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
607 + }
608 + }];
609 + if ( ! isOperationCompleted) {
610 + isRunLoopNested = YES;
611 + NSLog(@"Waiting...");
612 + CFRunLoopRun(); // Magic!
613 + isRunLoopNested = NO;
614 + }
615 + return resp;
616 +}
617 +
618 +- (NSDictionary*) deleteCard:(NSString*)token {
619 + __block NSDictionary *resp = [NSDictionary alloc];
620 + __block BOOL isRunLoopNested = NO;
621 + __block BOOL isOperationCompleted = NO;
622 + [[Warply sharedService] deleteCardWithSuccessBlock:token :^(NSDictionary *response) {
623 + resp = response;
624 + isOperationCompleted = YES;
625 + if (isRunLoopNested) {
626 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
627 + }
628 + } failureBlock:^(NSError *error) {
629 + NSLog(@"%@", error);
630 + resp = nil;
631 + isOperationCompleted = YES;
632 + if (isRunLoopNested) {
633 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
634 + }
635 + }];
636 + if ( ! isOperationCompleted) {
637 + isRunLoopNested = YES;
638 + NSLog(@"Waiting...");
639 + CFRunLoopRun(); // Magic!
640 + isRunLoopNested = NO;
641 + }
642 + return resp;
643 +}
644 +
645 +- (NSDictionary*) verifyTicket:(NSString*)guid ticket:(NSString*)ticket {
646 + __block NSDictionary *resp = [NSDictionary alloc];
647 + __block BOOL isRunLoopNested = NO;
648 + __block BOOL isOperationCompleted = NO;
649 + [[Warply sharedService] verifyTicketWithSuccessBlock:guid :ticket :^(NSDictionary *response) {
650 + resp = response;
651 + isOperationCompleted = YES;
652 + if (isRunLoopNested) {
653 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
654 + }
655 + } failureBlock:^(NSError *error) {
656 + NSLog(@"%@", error);
657 + resp = nil;
658 + isOperationCompleted = YES;
659 + if (isRunLoopNested) {
660 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
661 + }
662 + }];
663 + if ( ! isOperationCompleted) {
664 + isRunLoopNested = YES;
665 + NSLog(@"Waiting...");
666 + CFRunLoopRun(); // Magic!
667 + isRunLoopNested = NO;
668 + }
669 + return resp;
670 +}
671 +
672 +- (NSDictionary*) getCoupons {
673 + __block NSDictionary *resp = [NSDictionary alloc];
674 + __block BOOL isRunLoopNested = NO;
675 + __block BOOL isOperationCompleted = NO;
676 + [[Warply sharedService] getCouponsWithSuccessBlock:^(NSDictionary *response) {
677 + resp = response;
678 + isOperationCompleted = YES;
679 + if (isRunLoopNested) {
680 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
681 + }
682 + } failureBlock:^(NSError *error) {
683 + NSLog(@"%@", error);
684 + resp = nil;
685 + isOperationCompleted = YES;
686 + if (isRunLoopNested) {
687 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
688 + }
689 + }];
690 + if ( ! isOperationCompleted) {
691 + isRunLoopNested = YES;
692 + NSLog(@"Waiting...");
693 + CFRunLoopRun(); // Magic!
694 + isRunLoopNested = NO;
695 + }
696 + return resp;
697 +}
698 +
699 +- (NSDictionary*) getTransactionHistory {
700 + __block NSDictionary *resp = [NSDictionary alloc];
701 + __block BOOL isRunLoopNested = NO;
702 + __block BOOL isOperationCompleted = NO;
703 + [[Warply sharedService] getTransactionHistoryWithSuccessBlock:^(NSDictionary *response) {
704 + resp = response;
705 + isOperationCompleted = YES;
706 + if (isRunLoopNested) {
707 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
708 + }
709 + } failureBlock:^(NSError *error) {
710 + NSLog(@"%@", error);
711 + resp = nil;
712 + isOperationCompleted = YES;
713 + if (isRunLoopNested) {
714 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
715 + }
716 + }];
717 + if ( ! isOperationCompleted) {
718 + isRunLoopNested = YES;
719 + NSLog(@"Waiting...");
720 + CFRunLoopRun(); // Magic!
721 + isRunLoopNested = NO;
722 + }
723 + return resp;
724 +}
725 +
726 +- (NSDictionary*) getPointsHistory {
727 + __block NSDictionary *resp = [NSDictionary alloc];
728 + __block BOOL isRunLoopNested = NO;
729 + __block BOOL isOperationCompleted = NO;
730 + [[Warply sharedService] getPointsHistoryWithSuccessBlock:^(NSDictionary *response) {
731 + resp = response;
732 + isOperationCompleted = YES;
733 + if (isRunLoopNested) {
734 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
735 + }
736 + } failureBlock:^(NSError *error) {
737 + NSLog(@"%@", error);
738 + resp = nil;
739 + isOperationCompleted = YES;
740 + if (isRunLoopNested) {
741 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
742 + }
743 + }];
744 + if ( ! isOperationCompleted) {
745 + isRunLoopNested = YES;
746 + NSLog(@"Waiting...");
747 + CFRunLoopRun(); // Magic!
748 + isRunLoopNested = NO;
749 + }
750 + return resp;
751 +}
752 +
753 +- (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 {
754 + __block NSDictionary *resp = [NSDictionary alloc];
755 + __block BOOL isRunLoopNested = NO;
756 + __block BOOL isOperationCompleted = NO;
757 + [[Warply sharedService] addAddressWithSuccessBlock:friendlyName :addressName :addressNumber :postalCode :floorNumber :doorbel :region :latitude :longitude :notes :^(NSDictionary *response) {
758 + resp = response;
759 + isOperationCompleted = YES;
760 + if (isRunLoopNested) {
761 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
762 + }
763 + } failureBlock:^(NSError *error) {
764 + NSLog(@"%@", error);
765 + resp = nil;
766 + isOperationCompleted = YES;
767 + if (isRunLoopNested) {
768 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
769 + }
770 + }];
771 + if ( ! isOperationCompleted) {
772 + isRunLoopNested = YES;
773 + NSLog(@"Waiting...");
774 + CFRunLoopRun(); // Magic!
775 + isRunLoopNested = NO;
776 + }
777 + return resp;
778 +}
779 +
780 +- (NSDictionary*)getAddress{
781 + __block NSDictionary *resp = [NSDictionary alloc];
782 + __block BOOL isRunLoopNested = NO;
783 + __block BOOL isOperationCompleted = NO;
784 + [[Warply sharedService] getAddressWithSuccessBlock:^(NSDictionary *response) {
785 + resp = response;
786 + isOperationCompleted = YES;
787 + if (isRunLoopNested) {
788 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
789 + }
790 + } failureBlock:^(NSError *error) {
791 + NSLog(@"%@", error);
792 + resp = nil;
793 + isOperationCompleted = YES;
794 + if (isRunLoopNested) {
795 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
796 + }
797 + }];
798 + if ( ! isOperationCompleted) {
799 + isRunLoopNested = YES;
800 + NSLog(@"Waiting...");
801 + CFRunLoopRun(); // Magic!
802 + isRunLoopNested = NO;
803 + }
804 + return resp;
805 +}
806 +
807 +- (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 {
808 + __block NSDictionary *resp = [NSDictionary alloc];
809 + __block BOOL isRunLoopNested = NO;
810 + __block BOOL isOperationCompleted = NO;
811 + [[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) {
812 + resp = response;
813 + isOperationCompleted = YES;
814 + if (isRunLoopNested) {
815 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
816 + }
817 + } failureBlock:^(NSError *error) {
818 + NSLog(@"%@", error);
819 + resp = nil;
820 + isOperationCompleted = YES;
821 + if (isRunLoopNested) {
822 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
823 + }
824 + }];
825 + if ( ! isOperationCompleted) {
826 + isRunLoopNested = YES;
827 + NSLog(@"Waiting...");
828 + CFRunLoopRun(); // Magic!
829 + isRunLoopNested = NO;
830 + }
831 + return resp;
832 +}
833 +
834 +- (NSDictionary*)deleteAddress:(NSString*)uuid{
835 + __block NSDictionary *resp = [NSDictionary alloc];
836 + __block BOOL isRunLoopNested = NO;
837 + __block BOOL isOperationCompleted = NO;
838 + [[Warply sharedService] deleteAddressWithSuccessBlock:uuid :^(NSDictionary *response) {
839 + resp = response;
840 + isOperationCompleted = YES;
841 + if (isRunLoopNested) {
842 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
843 + }
844 + } failureBlock:^(NSError *error) {
845 + NSLog(@"%@", error);
846 + resp = nil;
847 + isOperationCompleted = YES;
848 + if (isRunLoopNested) {
849 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
850 + }
851 + }];
852 + if ( ! isOperationCompleted) {
853 + isRunLoopNested = YES;
854 + NSLog(@"Waiting...");
855 + CFRunLoopRun(); // Magic!
856 + isRunLoopNested = NO;
857 + }
858 + return resp;
859 +}
860 +
861 +- (NSDictionary*)redeemCoupon:(NSString*)id andUuid:(NSString*)uuid {
862 + __block NSDictionary *resp = [NSDictionary alloc];
863 + __block BOOL isRunLoopNested = NO;
864 + __block BOOL isOperationCompleted = NO;
865 + [[Warply sharedService] redeemCouponWithSuccessBlock:id andUuid:uuid :^(NSDictionary *response) {
866 + resp = response;
867 + isOperationCompleted = YES;
868 + if (isRunLoopNested) {
869 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
870 + }
871 + } failureBlock:^(NSError *error) {
872 + NSLog(@"%@", error);
873 + resp = nil;
874 + isOperationCompleted = YES;
875 + if (isRunLoopNested) {
876 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
877 + }
878 + }];
879 + if ( ! isOperationCompleted) {
880 + isRunLoopNested = YES;
881 + NSLog(@"Waiting...");
882 + CFRunLoopRun(); // Magic!
883 + isRunLoopNested = NO;
884 + }
885 + return resp;
886 +}
887 +
888 +- (NSDictionary*)forgotPasswordWithId:(NSString*)id andConfCode:(NSString*)confCode andOtpUuid:(NSString*)otpUuid {
889 + __block NSDictionary *resp = [NSDictionary alloc];
890 + __block BOOL isRunLoopNested = NO;
891 + __block BOOL isOperationCompleted = NO;
892 + [[Warply sharedService] forgotPasswordWithIdWithSuccessBlock:id andConfCode:confCode andOtpUuid:otpUuid :^(NSDictionary *response) {
893 + resp = response;
894 + isOperationCompleted = YES;
895 + if (isRunLoopNested) {
896 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
897 + }
898 + } failureBlock:^(NSError *error) {
899 + NSLog(@"%@", error);
900 + resp = nil;
901 + isOperationCompleted = YES;
902 + if (isRunLoopNested) {
903 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
904 + }
905 + }];
906 + if ( ! isOperationCompleted) {
907 + isRunLoopNested = YES;
908 + NSLog(@"Waiting...");
909 + CFRunLoopRun(); // Magic!
910 + isRunLoopNested = NO;
911 + }
912 + return resp;
913 +}
914 +
915 +- (NSDictionary*)resetPasswordWithPassword:(NSString*)password andConfCode:(NSString*)confCode andOtpUuid:(NSString*)otpUuid andConfToken:(NSString*)confToken {
916 + __block NSDictionary *resp = [NSDictionary alloc];
917 + __block BOOL isRunLoopNested = NO;
918 + __block BOOL isOperationCompleted = NO;
919 + [[Warply sharedService] resetPasswordWithPasswordWithSuccessBlock:password andConfCode:confCode andOtpUuid:otpUuid andConfToken:confToken :^(NSDictionary *response) {
920 + resp = response;
921 + isOperationCompleted = YES;
922 + if (isRunLoopNested) {
923 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
924 + }
925 + } failureBlock:^(NSError *error) {
926 + NSLog(@"%@", error);
927 + resp = nil;
928 + isOperationCompleted = YES;
929 + if (isRunLoopNested) {
930 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
931 + }
932 + }];
933 + if ( ! isOperationCompleted) {
934 + isRunLoopNested = YES;
935 + NSLog(@"Waiting...");
936 + CFRunLoopRun(); // Magic!
937 + isRunLoopNested = NO;
938 + }
939 + return resp;
940 +}
941 +
942 +- (NSDictionary*)requestOtpWithMsisdn:(NSString*)msisdn andScope:(NSString*)scope {
943 + __block NSDictionary *resp = [NSDictionary alloc];
944 + __block BOOL isRunLoopNested = NO;
945 + __block BOOL isOperationCompleted = NO;
946 + [[Warply sharedService] requestOtpWithMsisdnWithSuccessBlock:msisdn andScope:scope :^(NSDictionary *response) {
947 + resp = response;
948 + isOperationCompleted = YES;
949 + if (isRunLoopNested) {
950 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
951 + }
952 + } failureBlock:^(NSError *error) {
953 + NSLog(@"%@", error);
954 + resp = nil;
955 + isOperationCompleted = YES;
956 + if (isRunLoopNested) {
957 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
958 + }
959 + }];
960 + if ( ! isOperationCompleted) {
961 + isRunLoopNested = YES;
962 + NSLog(@"Waiting...");
963 + CFRunLoopRun(); // Magic!
964 + isRunLoopNested = NO;
965 + }
966 + return resp;
967 +}
968 +
969 +- (NSDictionary*)retrieveMultilingualMerchantsWithCategories:(NSArray*)categories andDefaultShown:(NSNumber*)defaultShown andCenter:(NSNumber*)center andTags:(NSArray*)tags andUuid:(NSString*)uuid andDistance:(NSNumber*)distance {
970 + __block NSDictionary *resp = [NSDictionary alloc];
971 + __block BOOL isRunLoopNested = NO;
972 + __block BOOL isOperationCompleted = NO;
973 + [[Warply sharedService] retrieveMultilingualMerchantsWithCategoriesWithSuccessBlock:categories andDefaultShown:defaultShown andCenter:center andTags:tags andUuid:uuid andDistance:distance :^(NSDictionary *response) {
974 + resp = response;
975 + isOperationCompleted = YES;
976 + if (isRunLoopNested) {
977 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
978 + }
979 + } failureBlock:^(NSError *error) {
980 + NSLog(@"%@", error);
981 + resp = nil;
982 + isOperationCompleted = YES;
983 + if (isRunLoopNested) {
984 + CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
985 + }
986 + }];
987 + if ( ! isOperationCompleted) {
988 + isRunLoopNested = YES;
989 + NSLog(@"Waiting...");
990 + CFRunLoopRun(); // Magic!
991 + isRunLoopNested = NO;
992 + }
993 + return resp;
994 +}
995 +@end
1 +//
2 +// ProfileView.swift
3 +// warplyFramework
4 +//
5 +// Created by Βασιλης Σκουρας on 13/1/22.
6 +//
7 +
8 +import SwiftUI
9 +
10 +@available(iOS 13.0.0, *)
11 +struct ProfileView: View {
12 +
13 + let uiscreen = UIScreen.main.bounds
14 + @State private var bottomRect: CGRect = .zero
15 + var body: some View {
16 + ScrollView {
17 + VStack {
18 +// var instanceOfMyApi = MyApi()
19 +// var myJson = instanceOfMyApi.getProfile() as AnyObject?
20 + ZStack {
21 + Image("logo", bundle: Bundle(identifier:"framework.warp.ly.warplySDKFrameworkIOS"))
22 + .resizable()
23 + .frame(width: self.uiscreen.height * 0.025, height: self.uiscreen.height * 0.02)
24 + .offset(x: -self.uiscreen.width / 2 + self.uiscreen.width * 0.05, y: self.uiscreen.height * 0.04)
25 + Text("Το προφίλ μου")
26 + .frame(width: self.uiscreen.width * 0.8, height: self.uiscreen.height * 0.025, alignment: .center)
27 + .offset( y: self.uiscreen.height * 0.04)
28 + }
29 + .frame(width: self.uiscreen.width)
30 +// Rectangle()
31 +//
32 +// .foregroundStyle(
33 +// .linearGradient(
34 +// 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))],
35 +// startPoint: .leading,
36 +// endPoint: .trailing
37 +// )
38 +// )
39 +//
40 +// .frame(width: self.uiscreen.width * 0.9,
41 +// height: self.uiscreen.height * 0.15,
42 +// alignment: .topLeading)
43 +// .cornerRadius(CGFloat(7))
44 +// .offset(x: self.uiscreen.width * 0.0025, y: self.uiscreen.height * 0.08)
45 + ZStack {
46 + Image("logo", bundle: Bundle(identifier:"framework.warp.ly.warplySDKFrameworkIOS"))
47 + .resizable()
48 + .frame(width: self.uiscreen.height * 0.04, height: self.uiscreen.height * 0.04, alignment: .topLeading)
49 + .cornerRadius(CGFloat(self.uiscreen.height * 0.02))
50 + .offset(x: -self.uiscreen.width / 2 + self.uiscreen.width * 0.14, y: -self.uiscreen.height * 0.07)
51 + Image("logo", bundle: Bundle(identifier:"framework.warp.ly.warplySDKFrameworkIOS"))
52 + .resizable()
53 + .frame(width: self.uiscreen.width * 0.24, height: self.uiscreen.height * 0.038, alignment: .topLeading)
54 + .cornerRadius(CGFloat(self.uiscreen.height * 0.02))
55 + .offset(x: self.uiscreen.width / 2 - self.uiscreen.width * 0.2, y: -self.uiscreen.height * 0.07)
56 + }
57 + Text("Χριστίνα Γεωργίου")
58 + .frame( width: self.uiscreen.width * 0.8, height: self.uiscreen.height * 0.04, alignment: .leading)
59 + .offset(y: -self.uiscreen.height * 0.03)
60 + .foregroundColor(.white)
61 + }
62 + Text("Ενεργά κουπόνια")
63 + .frame(width: self.uiscreen.width * 0.9, alignment: .leading)
64 +// .offset(x: -self.uiscreen.width / 4 + self.uiscreen.width * 0.0025)
65 +
66 + }
67 + .frame(width:self.uiscreen.width, height:self.uiscreen.height )
68 + }
69 +}
70 +
71 +struct ProfileView_Previews: PreviewProvider {
72 + static var previews: some View {
73 + ProfileView()
74 + }
75 +}
1 +//
2 +// ProfileViewController.swift
3 +// warplyFramework
4 +//
5 +// Created by Βασιλης Σκουρας on 14/1/22.
6 +//
7 +
8 +import Foundation
9 +import SwiftUI
10 +
11 +@available(iOS 13.0.0, *)
12 +@objc public class ProfileViewInterface : NSObject {
13 +
14 + @objc static public func profileViewController() -> UIViewController {
15 + return UIHostingController(rootView: ProfileView())
16 + }
17 +
18 +}
1 +# ``WarplySDKFrameworkIOS``
2 +
3 +<!--@START_MENU_TOKEN@-->Summary<!--@END_MENU_TOKEN@-->
4 +
5 +## Overview
6 +
7 +<!--@START_MENU_TOKEN@-->Text<!--@END_MENU_TOKEN@-->
8 +
9 +## Topics
10 +
11 +### <!--@START_MENU_TOKEN@-->Group<!--@END_MENU_TOKEN@-->
12 +
13 +- <!--@START_MENU_TOKEN@-->``Symbol``<!--@END_MENU_TOKEN@-->
...\ No newline at end of file ...\ No newline at end of file
1 +//
2 +// WarplySDKFrameworkIOS.h
3 +// WarplySDKFrameworkIOS
4 +//
5 +// Created by Βασιλης Σκουρας on 1/2/22.
6 +//
7 +
8 +#import <Foundation/Foundation.h>
9 +
10 +//! Project version number for WarplySDKFrameworkIOS.
11 +FOUNDATION_EXPORT double WarplySDKFrameworkIOSVersionNumber;
12 +
13 +//! Project version string for WarplySDKFrameworkIOS.
14 +FOUNDATION_EXPORT const unsigned char WarplySDKFrameworkIOSVersionString[];
15 +
16 +// In this header, you should import all the public headers of your framework using statements like #import <WarplySDKFrameworkIOS/PublicHeader.h>
17 +
18 +