Vasilis

erasing all

Showing 148 changed files with 0 additions and 4930 deletions
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 -}
1 -# Uncomment the next line to define a global platform for your project
2 -# platform :ios, '9.0'
3 -
4 -target 'warplySDKFramework' do
5 - # Comment the next line if you don't want to use dynamic frameworks
6 - use_frameworks!
7 -
8 - # Pods for warplySDKFramework
9 -
10 -end
1 -PODFILE CHECKSUM: b573ed0972ebe035cd00ae8c5846f47a6b7d22e9
2 -
3 -COCOAPODS: 1.11.2
1 -PODFILE CHECKSUM: b573ed0972ebe035cd00ae8c5846f47a6b7d22e9
2 -
3 -COCOAPODS: 1.11.2
This diff is collapsed. Click to expand it.
1 -<?xml version="1.0" encoding="UTF-8"?>
2 -<Scheme
3 - LastUpgradeVersion = "1240"
4 - version = "1.3">
5 - <BuildAction
6 - parallelizeBuildables = "YES"
7 - buildImplicitDependencies = "YES">
8 - <BuildActionEntries>
9 - <BuildActionEntry
10 - buildForTesting = "YES"
11 - buildForRunning = "YES"
12 - buildForProfiling = "YES"
13 - buildForArchiving = "YES"
14 - buildForAnalyzing = "YES">
15 - <BuildableReference
16 - BuildableIdentifier = "primary"
17 - BlueprintIdentifier = "3CFA2EEFF2D439AF0D4C650D73DE9491"
18 - BuildableName = "Pods_warplySDKFramework.framework"
19 - BlueprintName = "Pods-warplySDKFramework"
20 - ReferencedContainer = "container:Pods.xcodeproj">
21 - </BuildableReference>
22 - </BuildActionEntry>
23 - </BuildActionEntries>
24 - </BuildAction>
25 - <TestAction
26 - buildConfiguration = "Debug"
27 - selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
28 - selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
29 - shouldUseLaunchSchemeArgsEnv = "YES">
30 - <Testables>
31 - </Testables>
32 - </TestAction>
33 - <LaunchAction
34 - buildConfiguration = "Debug"
35 - selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
36 - selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
37 - launchStyle = "0"
38 - useCustomWorkingDirectory = "NO"
39 - ignoresPersistentStateOnLaunch = "NO"
40 - debugDocumentVersioning = "YES"
41 - debugServiceExtension = "internal"
42 - allowLocationSimulation = "YES">
43 - </LaunchAction>
44 - <ProfileAction
45 - buildConfiguration = "Release"
46 - shouldUseLaunchSchemeArgsEnv = "YES"
47 - savedToolIdentifier = ""
48 - useCustomWorkingDirectory = "NO"
49 - debugDocumentVersioning = "YES">
50 - </ProfileAction>
51 - <AnalyzeAction
52 - buildConfiguration = "Debug">
53 - </AnalyzeAction>
54 - <ArchiveAction
55 - buildConfiguration = "Release"
56 - revealArchiveInOrganizer = "YES">
57 - </ArchiveAction>
58 -</Scheme>
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>Pods-warplySDKFramework.xcscheme</key>
8 - <dict>
9 - <key>isShown</key>
10 - <false/>
11 - <key>orderHint</key>
12 - <integer>0</integer>
13 - </dict>
14 - </dict>
15 - <key>SuppressBuildableAutocreation</key>
16 - <dict/>
17 -</dict>
18 -</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>CFBundleDevelopmentRegion</key>
6 - <string>en</string>
7 - <key>CFBundleExecutable</key>
8 - <string>${EXECUTABLE_NAME}</string>
9 - <key>CFBundleIdentifier</key>
10 - <string>${PRODUCT_BUNDLE_IDENTIFIER}</string>
11 - <key>CFBundleInfoDictionaryVersion</key>
12 - <string>6.0</string>
13 - <key>CFBundleName</key>
14 - <string>${PRODUCT_NAME}</string>
15 - <key>CFBundlePackageType</key>
16 - <string>FMWK</string>
17 - <key>CFBundleShortVersionString</key>
18 - <string>1.0.0</string>
19 - <key>CFBundleSignature</key>
20 - <string>????</string>
21 - <key>CFBundleVersion</key>
22 - <string>${CURRENT_PROJECT_VERSION}</string>
23 - <key>NSPrincipalClass</key>
24 - <string></string>
25 -</dict>
26 -</plist>
1 -# Acknowledgements
2 -This application makes use of the following third party libraries:
3 -Generated by CocoaPods - https://cocoapods.org
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>PreferenceSpecifiers</key>
6 - <array>
7 - <dict>
8 - <key>FooterText</key>
9 - <string>This application makes use of the following third party libraries:</string>
10 - <key>Title</key>
11 - <string>Acknowledgements</string>
12 - <key>Type</key>
13 - <string>PSGroupSpecifier</string>
14 - </dict>
15 - <dict>
16 - <key>FooterText</key>
17 - <string>Generated by CocoaPods - https://cocoapods.org</string>
18 - <key>Title</key>
19 - <string></string>
20 - <key>Type</key>
21 - <string>PSGroupSpecifier</string>
22 - </dict>
23 - </array>
24 - <key>StringsTable</key>
25 - <string>Acknowledgements</string>
26 - <key>Title</key>
27 - <string>Acknowledgements</string>
28 -</dict>
29 -</plist>
1 -#import <Foundation/Foundation.h>
2 -@interface PodsDummy_Pods_warplySDKFramework : NSObject
3 -@end
4 -@implementation PodsDummy_Pods_warplySDKFramework
5 -@end
1 -#ifdef __OBJC__
2 -#import <UIKit/UIKit.h>
3 -#else
4 -#ifndef FOUNDATION_EXPORT
5 -#if defined(__cplusplus)
6 -#define FOUNDATION_EXPORT extern "C"
7 -#else
8 -#define FOUNDATION_EXPORT extern
9 -#endif
10 -#endif
11 -#endif
12 -
13 -
14 -FOUNDATION_EXPORT double Pods_warplySDKFrameworkVersionNumber;
15 -FOUNDATION_EXPORT const unsigned char Pods_warplySDKFrameworkVersionString[];
16 -
1 -CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO
2 -GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1
3 -PODS_BUILD_DIR = ${BUILD_DIR}
4 -PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)
5 -PODS_PODFILE_DIR_PATH = ${SRCROOT}/.
6 -PODS_ROOT = ${SRCROOT}/Pods
7 -PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates
8 -USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES
1 -framework module Pods_warplySDKFramework {
2 - umbrella header "Pods-warplySDKFramework-umbrella.h"
3 -
4 - export *
5 - module * { export * }
6 -}
1 -CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO
2 -GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1
3 -PODS_BUILD_DIR = ${BUILD_DIR}
4 -PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)
5 -PODS_PODFILE_DIR_PATH = ${SRCROOT}/.
6 -PODS_ROOT = ${SRCROOT}/Pods
7 -PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates
8 -USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES
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
This diff is collapsed. Click to expand it.
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
No preview for this file type
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
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 -*/
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
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
This diff is collapsed. Click to expand it.
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 -//
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"
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
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
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
No preview for this file type
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.