Manos Chorianopoulos

swift migration

Showing 336 changed files with 924 additions and 4066 deletions
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
1 +# SwiftWarplyFramework Quick Reference
2 +
3 +## 🚀 Essential Guide for Developers
4 +
5 +**Version**: 2.0.1 | **iOS**: 17.0+ | **Swift**: 5.0+
6 +
7 +---
8 +
9 +## 📦 Installation
10 +
11 +```ruby
12 +# Podfile
13 +pod 'SwiftWarplyFramework', '~> 2.0.1'
14 +```
15 +
16 +---
17 +
18 +## ⚡ Setup (AppDelegate)
19 +
20 +```swift
21 +import SwiftWarplyFramework
22 +
23 +// Configure & Initialize
24 +WarplySDK.shared.configure(webId: "your-web-id", merchantId: "your-merchant-id", environment: .production)
25 +WarplySDK.shared.initialize { success in
26 + print("SDK Ready: \(success)")
27 +}
28 +```
29 +
30 +---
31 +
32 +## 🔐 Authentication
33 +
34 +```swift
35 +// Login
36 +WarplySDK.shared.verifyTicket(guid: "user-guid", ticket: "user-ticket") { response in
37 + if response?.getStatus == 1 { /* Success */ }
38 +}
39 +
40 +// Async/Await
41 +let response = try await WarplySDK.shared.verifyTicket(guid: "guid", ticket: "ticket")
42 +
43 +// Logout
44 +WarplySDK.shared.logout { response in /* Handle logout */ }
45 +```
46 +
47 +---
48 +
49 +## 🎯 Campaigns
50 +
51 +```swift
52 +// Get Campaigns
53 +WarplySDK.shared.getCampaigns(language: "en") { campaigns in
54 + // Handle campaigns array
55 +}
56 +
57 +// Async/Await
58 +let campaigns = try await WarplySDK.shared.getCampaigns(language: "en")
59 +
60 +// Personalized Campaigns
61 +let personalizedCampaigns = try await WarplySDK.shared.getCampaignsPersonalized(language: "en")
62 +
63 +// Supermarket Campaign
64 +WarplySDK.shared.getSupermarketCampaign(language: "en") { campaign in
65 + // Handle supermarket campaign
66 +}
67 +```
68 +
69 +---
70 +
71 +## 🎫 Coupons
72 +
73 +```swift
74 +// Get Coupons
75 +WarplySDK.shared.getCoupons(language: "en", completion: { coupons in
76 + // Handle coupons
77 +}, failureCallback: { errorCode in
78 + // Handle error
79 +})
80 +
81 +// Async/Await
82 +let coupons = try await WarplySDK.shared.getCoupons(language: "en")
83 +
84 +// Coupon Sets
85 +let couponSets = try await WarplySDK.shared.getCouponSets()
86 +
87 +// Availability
88 +WarplySDK.shared.getAvailableCoupons { availability in
89 + // Handle availability data
90 +}
91 +```
92 +
93 +---
94 +
95 +## 🏪 Market Pass
96 +
97 +```swift
98 +// Market Pass Details
99 +WarplySDK.shared.getMarketPassDetails(completion: { marketPass in
100 + print("Balance: \(marketPass?.balance ?? 0)")
101 +}, failureCallback: { errorCode in
102 + // Handle error
103 +})
104 +
105 +// Async/Await
106 +let marketPass = try await WarplySDK.shared.getMarketPassDetails()
107 +
108 +// Supermarket History
109 +let history = try await WarplySDK.shared.getRedeemedSMHistory(language: "en")
110 +```
111 +
112 +---
113 +
114 +## 📡 Events
115 +
116 +### Modern EventDispatcher (Recommended)
117 +
118 +```swift
119 +class ViewController: UIViewController {
120 + private var eventSubscriptions: [EventSubscription] = []
121 +
122 + override func viewDidLoad() {
123 + super.viewDidLoad()
124 +
125 + // Subscribe to events
126 + let subscription = WarplySDK.shared.subscribe(CampaignsRetrievedEvent.self) { event in
127 + DispatchQueue.main.async {
128 + // Update UI
129 + }
130 + }
131 + eventSubscriptions.append(subscription)
132 + }
133 +
134 + deinit {
135 + eventSubscriptions.removeAll() // Auto cleanup
136 + }
137 +}
138 +```
139 +
140 +### Legacy SwiftEventBus
141 +
142 +```swift
143 +// Subscribe
144 +SwiftEventBus.onMainThread(self, name: "campaigns_retrieved") { result in
145 + // Handle event
146 +}
147 +
148 +// Cleanup
149 +deinit {
150 + SwiftEventBus.unregister(self)
151 +}
152 +```
153 +
154 +---
155 +
156 +## ⚠️ Error Handling
157 +
158 +```swift
159 +// Async/Await Error Handling
160 +Task {
161 + do {
162 + let campaigns = try await WarplySDK.shared.getCampaigns(language: "en")
163 + // Success
164 + } catch let error as WarplyError {
165 + switch error {
166 + case .networkError: // Handle network error
167 + case .authenticationFailed: // Handle auth error
168 + case .invalidResponse: // Handle invalid response
169 + case .dataParsingError: // Handle parsing error
170 + case .unknownError(let code): // Handle unknown error
171 + }
172 + }
173 +}
174 +```
175 +
176 +---
177 +
178 +## 📱 Push Notifications
179 +
180 +```swift
181 +// AppDelegate
182 +func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
183 + let tokenString = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
184 + WarplySDK.shared.updateDeviceToken(tokenString)
185 +}
186 +
187 +func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
188 + if WarplySDK.shared.checkForLoyaltySDKNotification(userInfo) {
189 + // Warply notification handled
190 + }
191 +}
192 +```
193 +
194 +---
195 +
196 +## ⚙️ Configuration Properties
197 +
198 +```swift
199 +// Language
200 +WarplySDK.shared.applicationLocale = "en" // or "el"
201 +
202 +// Dark Mode
203 +WarplySDK.shared.isDarkModeEnabled = true
204 +
205 +// Analytics
206 +WarplySDK.shared.trackersEnabled = true
207 +
208 +// Network Status
209 +let status = WarplySDK.shared.getNetworkStatus() // 1=connected, 0=disconnected, -1=unknown
210 +```
211 +
212 +---
213 +
214 +## 🎯 State Management
215 +
216 +```swift
217 +// Campaigns
218 +let campaigns = WarplySDK.shared.getCampaignList()
219 +let allCampaigns = WarplySDK.shared.getAllCampaignList()
220 +let carouselCampaigns = WarplySDK.shared.getCarouselList()
221 +
222 +// Coupons
223 +let activeCoupons = WarplySDK.shared.getCouponList()
224 +let usedCoupons = WarplySDK.shared.getOldCouponList()
225 +
226 +// Market Pass
227 +let marketPass = WarplySDK.shared.getMarketPassDetails()
228 +
229 +// Merchants
230 +let merchants = WarplySDK.shared.getMerchantList()
231 +```
232 +
233 +---
234 +
235 +## 🔧 Utilities
236 +
237 +```swift
238 +// Campaign URLs
239 +let url = WarplySDK.shared.constructCampaignUrl(campaign)
240 +let params = WarplySDK.shared.constructCampaignParams(campaign)
241 +
242 +// UI Helpers
243 +WarplySDK.shared.openSupermarketsMap(self) // Open map
244 +WarplySDK.shared.openSuperMarketsFlow(self) // Open flow
245 +WarplySDK.shared.showDialog(self, "Title", "Message") // Show alert
246 +```
247 +
248 +---
249 +
250 +## 🚨 Common Patterns
251 +
252 +### Loading Data with Cache
253 +
254 +```swift
255 +func loadCampaigns() {
256 + // Show cached data first
257 + let cached = WarplySDK.shared.getCampaignList()
258 + if !cached.isEmpty {
259 + updateUI(with: cached)
260 + }
261 +
262 + // Fetch fresh data
263 + Task {
264 + do {
265 + let fresh = try await WarplySDK.shared.getCampaigns(language: "en")
266 + updateUI(with: fresh)
267 + } catch {
268 + // Keep cached data on error
269 + }
270 + }
271 +}
272 +```
273 +
274 +### Batch API Calls
275 +
276 +```swift
277 +Task {
278 + async let campaigns = WarplySDK.shared.getCampaigns(language: "en")
279 + async let coupons = WarplySDK.shared.getCoupons(language: "en")
280 + async let marketPass = WarplySDK.shared.getMarketPassDetails()
281 +
282 + do {
283 + let (campaignData, couponData, marketData) = try await (campaigns, coupons, marketPass)
284 + // Update UI with all data
285 + } catch {
286 + // Handle errors
287 + }
288 +}
289 +```
290 +
291 +### Network Check Before API
292 +
293 +```swift
294 +func safeAPICall() {
295 + guard WarplySDK.shared.getNetworkStatus() == 1 else {
296 + showOfflineMessage()
297 + return
298 + }
299 +
300 + // Proceed with API call
301 + Task {
302 + let campaigns = try await WarplySDK.shared.getCampaigns(language: "en")
303 + // Handle success
304 + }
305 +}
306 +```
307 +
308 +---
309 +
310 +## 📋 Available Events
311 +
312 +| Event | Type | Description |
313 +|-------|------|-------------|
314 +| `campaigns_retrieved` | `CampaignsRetrievedEvent` | Campaigns loaded |
315 +| `coupons_fetched` | `CouponsRetrievedEvent` | Coupons loaded |
316 +| `market_pass_details_fetched` | `MarketPassDetailsEvent` | Market pass loaded |
317 +| `ccms_retrieved` | `CCMSRetrievedEvent` | CCMS campaigns loaded |
318 +| `seasonals_retrieved` | `SeasonalsRetrievedEvent` | Seasonal campaigns loaded |
319 +| `dynatrace` | `DynatraceEvent` | Analytics events |
320 +
321 +---
322 +
323 +## 🔍 Debug Info
324 +
325 +```swift
326 +print("SDK Version: 2.0.1")
327 +print("App UUID: \(WarplySDK.shared.appUuid)")
328 +print("Merchant ID: \(WarplySDK.shared.merchantId)")
329 +print("Language: \(WarplySDK.shared.applicationLocale)")
330 +print("Network: \(WarplySDK.shared.getNetworkStatus())")
331 +print("Dark Mode: \(WarplySDK.shared.isDarkModeEnabled)")
332 +```
333 +
334 +---
335 +
336 +## 💡 Best Practices
337 +
338 +**Initialize in AppDelegate**
339 +**Use async/await for new code**
340 +**Handle errors properly**
341 +**Check network status**
342 +**Use weak self in closures**
343 +**Clean up event subscriptions**
344 +**Cache data when possible**
345 +
346 +**Don't ignore errors**
347 +**Don't initialize in ViewControllers**
348 +**Don't create retain cycles**
349 +**Don't forget to unregister events**
350 +
351 +---
352 +
353 +**For detailed documentation, see [CLIENT_DOCUMENTATION.md](CLIENT_DOCUMENTATION.md)**
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
7 <key>Pods-SwiftWarplyFramework.xcscheme_^#shared#^_</key> 7 <key>Pods-SwiftWarplyFramework.xcscheme_^#shared#^_</key>
8 <dict> 8 <dict>
9 <key>orderHint</key> 9 <key>orderHint</key>
10 - <integer>1</integer> 10 + <integer>0</integer>
11 </dict> 11 </dict>
12 </dict> 12 </dict>
13 </dict> 13 </dict>
......
1 +{
2 + "originHash" : "12dce73308b76580a096b2ddc2db953ca534c29f52e5b13e15c81719afbc8e45",
3 + "pins" : [
4 + {
5 + "identity" : "rsbarcodes_swift",
6 + "kind" : "remoteSourceControl",
7 + "location" : "https://github.com/yeahdongcn/RSBarcodes_Swift",
8 + "state" : {
9 + "revision" : "241de72a96f49b1545d5de3c00fae170c2675c41",
10 + "version" : "5.2.0"
11 + }
12 + },
13 + {
14 + "identity" : "swifteventbus",
15 + "kind" : "remoteSourceControl",
16 + "location" : "https://github.com/cesarferreira/SwiftEventBus",
17 + "state" : {
18 + "revision" : "a30ff35e616f507d8a8d122dac32a2150371a87e",
19 + "version" : "5.1.0"
20 + }
21 + }
22 + ],
23 + "version" : 3
24 +}
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
7 <key>SwiftWarplyFramework.xcscheme_^#shared#^_</key> 7 <key>SwiftWarplyFramework.xcscheme_^#shared#^_</key>
8 <dict> 8 <dict>
9 <key>orderHint</key> 9 <key>orderHint</key>
10 - <integer>0</integer> 10 + <integer>1</integer>
11 </dict> 11 </dict>
12 </dict> 12 </dict>
13 </dict> 13 </dict>
......
This diff is collapsed. Click to expand it.
1 +//
2 +// EventDispatcher.swift
3 +// SwiftWarplyFramework
4 +//
5 +// Created by Warply on 10/06/2025.
6 +// Copyright © 2025 Warply. All rights reserved.
7 +//
8 +
9 +import Foundation
10 +
11 +// MARK: - Event Protocol
12 +
13 +/// Base protocol for all Warply events
14 +public protocol WarplyEvent {
15 + /// Unique identifier for the event type
16 + var name: String { get }
17 + /// Timestamp when the event was created
18 + var timestamp: Date { get }
19 + /// Optional data payload for the event
20 + var data: Any? { get }
21 +}
22 +
23 +// MARK: - Event Subscription
24 +
25 +/// Represents a subscription to an event
26 +public final class EventSubscription {
27 + let id: UUID
28 + let eventName: String
29 + weak var dispatcher: EventDispatcher?
30 +
31 + init(id: UUID, eventName: String, dispatcher: EventDispatcher) {
32 + self.id = id
33 + self.eventName = eventName
34 + self.dispatcher = dispatcher
35 + }
36 +
37 + /// Unsubscribe from the event
38 + public func unsubscribe() {
39 + dispatcher?.unsubscribe(self)
40 + }
41 +
42 + deinit {
43 + unsubscribe()
44 + }
45 +}
46 +
47 +// MARK: - Event Dispatcher
48 +
49 +/// Modern Swift event dispatcher to replace SwiftEventBus
50 +public final class EventDispatcher {
51 +
52 + // MARK: - Singleton
53 + public static let shared = EventDispatcher()
54 +
55 + // MARK: - Private Properties
56 + private var subscribers: [String: [UUID: (Any) -> Void]] = [:]
57 + private let queue = DispatchQueue(label: "com.warply.eventdispatcher", attributes: .concurrent)
58 +
59 + // MARK: - Initialization
60 + private init() {}
61 +
62 + // MARK: - Public Methods
63 +
64 + /// Post an event to all subscribers
65 + /// - Parameter event: The event to post
66 + public func post<T: WarplyEvent>(_ event: T) {
67 + queue.async(flags: .barrier) {
68 + let eventName = event.name
69 +
70 + if let eventSubscribers = self.subscribers[eventName] {
71 + DispatchQueue.main.async {
72 + for handler in eventSubscribers.values {
73 + handler(event)
74 + }
75 + }
76 + }
77 + }
78 + }
79 +
80 + /// Post an event with string name and optional sender (for backward compatibility)
81 + /// - Parameters:
82 + /// - eventName: Name of the event
83 + /// - sender: Optional sender object
84 + public func post(_ eventName: String, sender: Any? = nil) {
85 + let event = GenericWarplyEvent(name: eventName, data: sender)
86 + post(event)
87 + }
88 +
89 + /// Subscribe to events of a specific type
90 + /// - Parameters:
91 + /// - eventType: The type of event to subscribe to
92 + /// - handler: The handler to call when the event is posted
93 + /// - Returns: An EventSubscription that can be used to unsubscribe
94 + @discardableResult
95 + public func subscribe<T: WarplyEvent>(_ eventType: T.Type, handler: @escaping (T) -> Void) -> EventSubscription {
96 + let eventName = String(describing: eventType)
97 + return subscribe(eventName) { event in
98 + if let typedEvent = event as? T {
99 + handler(typedEvent)
100 + }
101 + }
102 + }
103 +
104 + /// Subscribe to events by name (for backward compatibility)
105 + /// - Parameters:
106 + /// - eventName: Name of the event to subscribe to
107 + /// - handler: The handler to call when the event is posted
108 + /// - Returns: An EventSubscription that can be used to unsubscribe
109 + @discardableResult
110 + public func subscribe(_ eventName: String, handler: @escaping (Any) -> Void) -> EventSubscription {
111 + let subscriptionId = UUID()
112 +
113 + queue.async(flags: .barrier) {
114 + if self.subscribers[eventName] == nil {
115 + self.subscribers[eventName] = [:]
116 + }
117 + self.subscribers[eventName]?[subscriptionId] = handler
118 + }
119 +
120 + return EventSubscription(id: subscriptionId, eventName: eventName, dispatcher: self)
121 + }
122 +
123 + /// Unsubscribe from an event
124 + /// - Parameter subscription: The subscription to remove
125 + public func unsubscribe(_ subscription: EventSubscription) {
126 + queue.async(flags: .barrier) {
127 + self.subscribers[subscription.eventName]?.removeValue(forKey: subscription.id)
128 +
129 + // Clean up empty event arrays
130 + if self.subscribers[subscription.eventName]?.isEmpty == true {
131 + self.subscribers.removeValue(forKey: subscription.eventName)
132 + }
133 + }
134 + }
135 +
136 + /// Remove all subscribers for a specific event name
137 + /// - Parameter eventName: The event name to clear
138 + public func removeAllSubscribers(for eventName: String) {
139 + queue.async(flags: .barrier) {
140 + self.subscribers.removeValue(forKey: eventName)
141 + }
142 + }
143 +
144 + /// Remove all subscribers
145 + public func removeAllSubscribers() {
146 + queue.async(flags: .barrier) {
147 + self.subscribers.removeAll()
148 + }
149 + }
150 +}
151 +
152 +// MARK: - Specific Event Types
153 +
154 +/// Generic event for backward compatibility with string-based events
155 +public struct GenericWarplyEvent: WarplyEvent {
156 + public let name: String
157 + public let timestamp: Date
158 + public let data: Any?
159 +
160 + public init(name: String, data: Any? = nil) {
161 + self.name = name
162 + self.timestamp = Date()
163 + self.data = data
164 + }
165 +}
166 +
167 +/// Dynatrace analytics event
168 +public struct DynatraceEvent: WarplyEvent {
169 + public let name: String = "dynatrace"
170 + public let timestamp: Date
171 + public let data: Any?
172 +
173 + public init(data: Any? = nil) {
174 + self.timestamp = Date()
175 + self.data = data
176 + }
177 +}
178 +
179 +/// Campaigns retrieved event
180 +public struct CampaignsRetrievedEvent: WarplyEvent {
181 + public let name: String = "campaigns_retrieved"
182 + public let timestamp: Date
183 + public let data: Any?
184 +
185 + public init(data: Any? = nil) {
186 + self.timestamp = Date()
187 + self.data = data
188 + }
189 +}
190 +
191 +/// Market pass details fetched event
192 +public struct MarketPassDetailsEvent: WarplyEvent {
193 + public let name: String = "market_pass_details_fetched"
194 + public let timestamp: Date
195 + public let data: Any?
196 +
197 + public init(data: Any? = nil) {
198 + self.timestamp = Date()
199 + self.data = data
200 + }
201 +}
202 +
203 +/// CCMS campaigns retrieved event
204 +public struct CCMSRetrievedEvent: WarplyEvent {
205 + public let name: String = "ccms_retrieved"
206 + public let timestamp: Date
207 + public let data: Any?
208 +
209 + public init(data: Any? = nil) {
210 + self.timestamp = Date()
211 + self.data = data
212 + }
213 +}
214 +
215 +/// Seasonal campaigns retrieved event
216 +public struct SeasonalsRetrievedEvent: WarplyEvent {
217 + public let name: String = "seasonals_retrieved"
218 + public let timestamp: Date
219 + public let data: Any?
220 +
221 + public init(data: Any? = nil) {
222 + self.timestamp = Date()
223 + self.data = data
224 + }
225 +}
226 +
227 +/// Coupons fetched event
228 +public struct CouponsRetrievedEvent: WarplyEvent {
229 + public let name: String = "coupons_fetched"
230 + public let timestamp: Date
231 + public let data: Any?
232 +
233 + public init(data: Any? = nil) {
234 + self.timestamp = Date()
235 + self.data = data
236 + }
237 +}
238 +
239 +// MARK: - Convenience Extensions
240 +
241 +extension EventDispatcher {
242 +
243 + /// Post a dynatrace event
244 + /// - Parameter sender: The event data
245 + public func postDynatraceEvent(sender: Any? = nil) {
246 + post(DynatraceEvent(data: sender))
247 + }
248 +
249 + /// Post a campaigns retrieved event
250 + /// - Parameter sender: The event data
251 + public func postCampaignsRetrievedEvent(sender: Any? = nil) {
252 + post(CampaignsRetrievedEvent(data: sender))
253 + }
254 +
255 + /// Post a market pass details event
256 + /// - Parameter sender: The event data
257 + public func postMarketPassDetailsEvent(sender: Any? = nil) {
258 + post(MarketPassDetailsEvent(data: sender))
259 + }
260 +
261 + /// Post a CCMS retrieved event
262 + /// - Parameter sender: The event data
263 + public func postCCMSRetrievedEvent(sender: Any? = nil) {
264 + post(CCMSRetrievedEvent(data: sender))
265 + }
266 +
267 + /// Post a seasonals retrieved event
268 + /// - Parameter sender: The event data
269 + public func postSeasonalsRetrievedEvent(sender: Any? = nil) {
270 + post(SeasonalsRetrievedEvent(data: sender))
271 + }
272 +
273 + /// Post a coupons retrieved event
274 + /// - Parameter sender: The event data
275 + public func postCouponsRetrievedEvent(sender: Any? = nil) {
276 + post(CouponsRetrievedEvent(data: sender))
277 + }
278 +}
...@@ -7,30 +7,27 @@ ...@@ -7,30 +7,27 @@
7 // 7 //
8 8
9 #import "WarplyReactMethods.h" 9 #import "WarplyReactMethods.h"
10 -#import "WLUserManager.h" 10 +#import <UIKit/UIKit.h>
11 -#import "WLAnalyticsManager.h"
12 -#import "Warply.h"
13 #import <AdSupport/AdSupport.h> 11 #import <AdSupport/AdSupport.h>
14 12
15 @implementation WarplyReactMethods 13 @implementation WarplyReactMethods
14 +
16 - (void) sendEvent: (NSString *) eventName priority: (BOOL) priority { 15 - (void) sendEvent: (NSString *) eventName priority: (BOOL) priority {
17 - NSString *event_Name = eventName; 16 + // React Native bridge for event logging
18 - NSNumber *time_submitted = [NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]]; 17 + // Note: This is a simplified implementation for React Native compatibility
19 - NSDictionary *inapp_event = [NSDictionary dictionaryWithObjectsAndKeys:event_Name, @"event_id", nil, @"page_id", time_submitted, @"time_submitted", nil, @"action_metadata", nil]; 18 + // The actual event logging is now handled by the Swift WarplySDK
20 - NSDictionary *eventContext = [NSDictionary dictionaryWithObject:inapp_event forKey:@"inapp_analytics"]; 19 + NSLog(@"React Native Event: %@ (priority: %@)", eventName, priority ? @"YES" : @"NO");
21 - WLEventSimple *simpleEvent = [[WLEventSimple alloc] initWithType:@"inapp_analytics" andContext:eventContext]; 20 +
22 - 21 + // TODO: Bridge to Swift WarplySDK.shared.logTrackersEvent if needed
23 - [[Warply sharedService] addEvent:simpleEvent priority:priority]; 22 + // For now, this provides basic React Native compatibility
24 } 23 }
25 24
26 - (NSString *) getUniqueId { 25 - (NSString *) getUniqueId {
27 return [[[UIDevice currentDevice] identifierForVendor] UUIDString]; 26 return [[[UIDevice currentDevice] identifierForVendor] UUIDString];
28 } 27 }
29 28
30 -
31 - (NSString *) getAdvertisementId { 29 - (NSString *) getAdvertisementId {
32 return [[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString]; 30 return [[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString];
33 } 31 }
34 32
35 -
36 @end 33 @end
......
1 -//
2 -// MyApi.h
3 -// warplyFramework
4 -//
5 -// Created by Βασιλης Σκουρας on 8/12/21.
6 -//
7 -
8 -#ifndef MyApi_h
9 -#define MyApi_h
10 -#import <UIKit/UIKit.h>
11 -#import <CoreMotion/CoreMotion.h>
12 -@class Warply;
13 -
14 -@interface MyApi : NSObject
15 -
16 -@property (nonatomic, weak) Warply *warply;
17 -
18 -- (void) initialize:(NSDictionary *)launchOptions uuid:(NSString*)uuid merchantId:(NSString*)merchantId lang:(NSString*)lang;
19 -- (void) initializeWithCallback:(NSDictionary *)launchOptions uuid:(NSString*)uuid merchantId:(NSString*)merchantId lang:(NSString*)lang successBlock:(void(^)(NSDictionary *successBlock))success failureBlock:(void(^)(NSError *error))failure;
20 -- (void) setToStage;
21 -- (void) setLang:(NSString*) lang;
22 -- (void) getSteps:(void(^)(CMPedometerData* stepsData)) completion;
23 -- (void) startTrackingSteps:(void(^)(NSNumber * _Nullable numberOfSteps))callback;
24 -- (void) stopTrackingSteps;
25 -// - (UIViewController *) openCoupons:(UIView*) parentView;
26 -//- (UIViewController *) openCoupon:(UIView*) parentView coupon:(NSDictionary*) coupon;
27 -//- (UIViewController *) openCouponBarcode:(UIView*) parentView coupon:(NSDictionary*) coupon;
28 -//- (UIViewController *) openGifts:(UIView*) parentView;
29 -//- (UIViewController *) openAllGifts:(UIView*) parentView;
30 -//- (UIViewController *) openOldCoupons:(UIView*) parentView;
31 -//- (UIViewController *) openWallet:(UIView*) parentView;
32 -//- (UIViewController *) openMoreForYou:(UIView*) parentView;
33 -//- (UIViewController *) openCampaign:(UIView*) parentView campaign:(NSString*) campaign;
34 -//- (UIViewController *) openSteps:(UIView*) parentView;
35 -//- (UIViewController *) openDetails:(UIView*) parentView;
36 -- (NSDictionary *) provideInfoForCampaign;
37 -- (void) applicationDidEnterBackground:(UIApplication *)application;
38 -- (void) applicationWillEnterForeground:(UIApplication *)application;
39 -- (void) applicationDidBecomeActive:(UIApplication *)application;
40 -- (void) applicationWillTerminate:(UIApplication *)application;
41 -- (void) application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken;
42 -- (void) application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error;
43 -- (void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo;
44 -- (NSMutableArray *)getProducts:(NSString *) filter;
45 -- (NSMutableArray*)sendContact:(NSString*)name email:(NSString*)email msisdn:(NSString*)msisdn message:(NSString*)message;
46 -- (NSMutableArray *)getContentWithCategory:(NSString *)category tags:(NSArray *)tags;
47 -- (NSMutableArray *)getMerchantCategories;
48 -- (NSMutableArray *)getMerchants;
49 -- (NSMutableArray *)getTagsCategories;
50 -- (NSMutableArray *)getTags;
51 -- (NSDictionary *)login:(NSString *)id password:(NSString *)password loginType:(NSString*) loginType;
52 -// - (NSDictionary *)logout;
53 -- (void) logout:(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
54 -- (NSDictionary *)register:(NSString *)id password:(NSString *)password name:(NSString*)name email:(NSString*)email segmentation:(NSNumber*)segmentation newsletter:(NSNumber*)newsletter;
55 -- (NSDictionary *)registerAutoLogin:(NSString *)id password:(NSString *)password name:(NSString*)name email:(NSString*)email segmentation:(NSNumber*)segmentation newsletter:(NSNumber*)newsletter loginType:(NSString*)loginType;
56 -- (NSDictionary *)refreshToken;
57 -- (NSDictionary *)changePassword:(NSString *)oldPassword newPassword:(NSString *)newPassword;
58 -- (NSDictionary *)changeProfileImage:(NSString*)image andUserId:(NSString*)userId;
59 -- (NSDictionary*) addCard:(NSString*)number andCardIssuer:(NSString*)cardIssuer andCardHolder:(NSString*)cardHolder andExpirationMonth:(NSString*)expirationMonth andExpirationYear:(NSString*)expirationYear;
60 -- (NSDictionary*) getCards;
61 -- (NSDictionary*) deleteCard:(NSString*)token;
62 -- (NSDictionary*) verifyTicket:(NSString*)guid ticket:(NSString*)ticket;
63 -- (NSDictionary*) getTransactionHistory;
64 -- (NSDictionary*) getPointsHistory;
65 -- (NSDictionary*)addAddress:(NSString*)friendlyName andAddressName:(NSString*)addressName andAddressNumber:(NSString*)addressNumber andPostalCode:(NSString*)postalCode andFloorNumber:(NSNumber*)floorNumber andDoorbell:(NSString*)doorbel andRegion:(NSString*)region andLatitude:(NSString*)latitude andLongitude:(NSString*)longitude andNotes:(NSString*)notes;
66 -- (NSDictionary*)getAddress;
67 -- (NSDictionary*)editAddress:(NSString*)friendlyName andAddressName:(NSString*)addressName andAddressNumber:(NSString*)addressNumber andPostalCode:(NSString*)postalCode andFloorNumber:(NSNumber*)floorNumber andDoorbell:(NSString*)doorbel andRegion:(NSString*)region andLatitude:(NSString*)latitude andLongitude:(NSString*)longitude andNotes:(NSString*)notes andUuid:(NSString*)uuid;
68 -- (NSDictionary*)deleteAddress:(NSString*)uuid;
69 -- (NSDictionary*)redeemCoupon:(NSString*)id andUuid:(NSString*)uuid;
70 -- (NSDictionary*)forgotPasswordWithId:(NSString*)id andConfCode:(NSString*)confCode andOtpUuid:(NSString*)otpUuid;
71 -- (NSDictionary*)resetPasswordWithPassword:(NSString*)password andConfCode:(NSString*)confCode andOtpUuid:(NSString*)otpUuid andConfToken:(NSString*)confToken;
72 -- (NSDictionary*)requestOtpWithMsisdn:(NSString*)msisdn andScope:(NSString*)scope;
73 -- (NSDictionary*)retrieveMultilingualMerchantsWithCategories:(NSArray*)categories andDefaultShown:(NSNumber*)defaultShown andCenter:(NSNumber*)center andTags:(NSArray*)tags andUuid:(NSString*)uuid andDistance:(NSNumber*)distance;
74 -- (NSDictionary*)getCouponSetsWithActive:(NSNumber*)active andVisible:(NSNumber*)visible andUuids:(NSArray*)uuids;
75 -- (NSDictionary*)validateCouponWithCoupon:(NSString*)coupon;
76 -- (NSDictionary*)loginCosmoteWithGuid:(NSString*)guid andAppUuid:(NSString*)appUuid andTicket:(NSString*)ticket;
77 -- (void)getCouponsUniversalAsync:(NSString*)language :(NSString*)couponsetType :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
78 -- (void) getAvailableCouponsAsync:(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
79 -- (void)getCouponsetsAsync:(NSNumber*) active andVisible:(NSNumber*) visible andUuids:(NSArray*) uuids :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
80 -- (void)verifyTicketAsync:(NSString*)guid :(NSString*)ticket :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
81 -- (void)getMarketPassDetailsAsync:(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
82 -- (void)getCosmoteUserAsync:(NSString*)guid :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
83 -- (void)getCampaignsAsyncNew:(NSString*)language :(NSDictionary*)filters :(void (^)(NSDictionary *response))success failureBlock:(void (^)(NSError *error))failure;
84 -- (void)getCampaignsPersonalizedAsync:(NSString*)language :(NSDictionary*)filters :(void (^)(NSDictionary *response))success failureBlock:(void (^)(NSError *error))failure;
85 -- (void)getMultilingualMerchantsAsync:(NSArray*)categories andDefaultShown:(NSNumber*)defaultShown andCenter:(NSNumber*)center andTags:(NSArray*)tags andUuid:(NSString*)uuid andDistance:(NSNumber*)distance parent_uuids:(NSArray*)parent_uuids :(void (^)(NSDictionary *response))success failureBlock:(void (^)(NSError *error))failure;
86 -// - (void)didReceiveNotification:(NSDictionary *)userInfo whileAppWasInState:(WLApplicationState)state;
87 -- (void)didReceiveNotification:(NSDictionary *)payload;
88 -- (BOOL)checkforLoyaltySDKNotification:(NSDictionary *)payload;
89 -//- (NSNumber*)checkforLoyaltySDKNotification:(NSDictionary *)payload;
90 -// TEST CODE FOR PUSH
91 -// - (BOOL)checkforLoyaltySDKNotification:(NSDictionary *)payload whileAppWasInState:(UIApplicationState)appState;
92 -// TEST CODE FOR PUSH
93 -// - (BOOL)checkforLoyaltySDKNotification:(NSDictionary *)payload :(void(^)(NSNumber *successResponse))success failureBlock:(void(^)(NSNumber *failureResponse))failure;
94 -- (void)sendDeviceInfoIfNecessary:(NSString *)newDeviceToken;
95 -- (BOOL)sdkInitialised;
96 -- (void)getSingleCampaignAsync:(NSString*)sessionUuid :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
97 -- (void) sendEvent: (NSString *) eventName priority: (BOOL) priority;
98 -- (void)updateRefreshTokenMA:(NSString*)access_token :(NSString*)refresh_token;
99 -- (NSString*)getAccessTokenM;
100 -- (long)getNetworkStatusM;
101 -
102 -@end
103 -#endif /* MyApi_h */
This diff is collapsed. Click to expand it.
1 +//
2 +// Endpoints.swift
3 +// SwiftWarplyFramework
4 +//
5 +// Created by Warply on 06/06/2025.
6 +// Copyright © 2025 Warply. All rights reserved.
7 +//
8 +
9 +import Foundation
10 +
11 +// MARK: - HTTP Method
12 +
13 +public enum HTTPMethod: String {
14 + case GET = "GET"
15 + case POST = "POST"
16 + case PUT = "PUT"
17 + case DELETE = "DELETE"
18 + case PATCH = "PATCH"
19 +}
20 +
21 +// MARK: - API Endpoints
22 +
23 +public enum Endpoint {
24 + // Authentication
25 + case verifyTicket(guid: String, ticket: String)
26 + case logout
27 + case getCosmoteUser(guid: String)
28 +
29 + // Campaigns
30 + case getCampaigns(language: String, filters: [String: Any])
31 + case getCampaignsPersonalized(language: String, filters: [String: Any])
32 + case getSingleCampaign(sessionUuid: String)
33 +
34 + // Coupons
35 + case getCoupons(language: String, couponsetType: String)
36 + case getCouponSets(active: Bool, visible: Bool, uuids: [String]?)
37 + case getAvailableCoupons
38 +
39 + // Market & Merchants
40 + case getMarketPassDetails
41 + case getMerchants(categories: [String], defaultShown: Bool, center: Double, tags: [String], uuid: String, distance: Int, parentUuids: [String])
42 +
43 + // Events
44 + case sendEvent(eventName: String, priority: Bool)
45 +
46 + // Device
47 + case sendDeviceInfo(deviceToken: String)
48 +
49 + // Network status
50 + case getNetworkStatus
51 +
52 + // MARK: - Endpoint Properties
53 +
54 + public var path: String {
55 + switch self {
56 + case .verifyTicket:
57 + return "/verify_ticket"
58 + case .logout:
59 + return "/logout"
60 + case .getCosmoteUser:
61 + return "/get_cosmote_user"
62 + case .getCampaigns:
63 + return "/get_campaigns"
64 + case .getCampaignsPersonalized:
65 + return "/get_campaigns_personalized"
66 + case .getSingleCampaign:
67 + return "/get_single_campaign"
68 + case .getCoupons:
69 + return "/get_coupons"
70 + case .getCouponSets:
71 + return "/get_coupon_sets"
72 + case .getAvailableCoupons:
73 + return "/get_available_coupons"
74 + case .getMarketPassDetails:
75 + return "/get_market_pass_details"
76 + case .getMerchants:
77 + return "/get_merchants"
78 + case .sendEvent:
79 + return "/send_event"
80 + case .sendDeviceInfo:
81 + return "/send_device_info"
82 + case .getNetworkStatus:
83 + return "/network_status"
84 + }
85 + }
86 +
87 + public var method: HTTPMethod {
88 + switch self {
89 + case .verifyTicket, .logout, .getCampaigns, .getCampaignsPersonalized,
90 + .getSingleCampaign, .getCoupons, .getCouponSets, .getAvailableCoupons,
91 + .getMarketPassDetails, .getMerchants, .sendEvent, .sendDeviceInfo:
92 + return .POST
93 + case .getCosmoteUser, .getNetworkStatus:
94 + return .GET
95 + }
96 + }
97 +
98 + public var parameters: [String: Any]? {
99 + switch self {
100 + case .verifyTicket(let guid, let ticket):
101 + return [
102 + "guid": guid,
103 + "ticket": ticket
104 + ]
105 +
106 + case .logout:
107 + return [:]
108 +
109 + case .getCosmoteUser(let guid):
110 + return [
111 + "guid": guid
112 + ]
113 +
114 + case .getCampaigns(let language, let filters):
115 + var params: [String: Any] = [
116 + "language": language
117 + ]
118 + // Merge filters into params
119 + for (key, value) in filters {
120 + params[key] = value
121 + }
122 + return params
123 +
124 + case .getCampaignsPersonalized(let language, let filters):
125 + var params: [String: Any] = [
126 + "language": language
127 + ]
128 + // Merge filters into params
129 + for (key, value) in filters {
130 + params[key] = value
131 + }
132 + return params
133 +
134 + case .getSingleCampaign(let sessionUuid):
135 + return [
136 + "session_uuid": sessionUuid
137 + ]
138 +
139 + case .getCoupons(let language, let couponsetType):
140 + return [
141 + "language": language,
142 + "couponset_type": couponsetType
143 + ]
144 +
145 + case .getCouponSets(let active, let visible, let uuids):
146 + var params: [String: Any] = [
147 + "active": active,
148 + "visible": visible
149 + ]
150 + if let uuids = uuids {
151 + params["uuids"] = uuids
152 + }
153 + return params
154 +
155 + case .getAvailableCoupons:
156 + return [:]
157 +
158 + case .getMarketPassDetails:
159 + return [:]
160 +
161 + case .getMerchants(let categories, let defaultShown, let center, let tags, let uuid, let distance, let parentUuids):
162 + return [
163 + "categories": categories,
164 + "default_shown": defaultShown,
165 + "center": center,
166 + "tags": tags,
167 + "uuid": uuid,
168 + "distance": distance,
169 + "parent_uuids": parentUuids
170 + ]
171 +
172 + case .sendEvent(let eventName, let priority):
173 + return [
174 + "event_name": eventName,
175 + "priority": priority
176 + ]
177 +
178 + case .sendDeviceInfo(let deviceToken):
179 + return [
180 + "device_token": deviceToken
181 + ]
182 +
183 + case .getNetworkStatus:
184 + return nil
185 + }
186 + }
187 +
188 + public var headers: [String: String] {
189 + var defaultHeaders = [
190 + "Content-Type": "application/json",
191 + "Accept": "application/json"
192 + ]
193 +
194 + // Add authentication headers if needed
195 + // This will be handled by the NetworkService
196 +
197 + return defaultHeaders
198 + }
199 +
200 + public var requiresAuthentication: Bool {
201 + switch self {
202 + case .verifyTicket, .getCosmoteUser, .getNetworkStatus:
203 + return false
204 + default:
205 + return true
206 + }
207 + }
208 +}
209 +
210 +// MARK: - Network Error
211 +
212 +public enum NetworkError: Error, LocalizedError {
213 + case invalidURL
214 + case noData
215 + case decodingError(Error)
216 + case serverError(Int)
217 + case networkError(Error)
218 + case authenticationRequired
219 + case invalidResponse
220 +
221 + public var errorDescription: String? {
222 + switch self {
223 + case .invalidURL:
224 + return "Invalid URL"
225 + case .noData:
226 + return "No data received"
227 + case .decodingError(let error):
228 + return "Decoding error: \(error.localizedDescription)"
229 + case .serverError(let code):
230 + return "Server error with code: \(code)"
231 + case .networkError(let error):
232 + return "Network error: \(error.localizedDescription)"
233 + case .authenticationRequired:
234 + return "Authentication required"
235 + case .invalidResponse:
236 + return "Invalid response"
237 + }
238 + }
239 +
240 + public var code: Int {
241 + switch self {
242 + case .invalidURL:
243 + return -1001
244 + case .noData:
245 + return -1002
246 + case .decodingError:
247 + return -1003
248 + case .serverError(let code):
249 + return code
250 + case .networkError(let error):
251 + return (error as NSError).code
252 + case .authenticationRequired:
253 + return 401
254 + case .invalidResponse:
255 + return -1004
256 + }
257 + }
258 +}
...@@ -6,7 +6,6 @@ ...@@ -6,7 +6,6 @@
6 // 6 //
7 7
8 #import <Foundation/Foundation.h> 8 #import <Foundation/Foundation.h>
9 -#import "MyApi.h"
10 9
11 //! Project version number for SwiftWarplyFramework. 10 //! Project version number for SwiftWarplyFramework.
12 FOUNDATION_EXPORT double SwiftWarplyFrameworkVersionNumber; 11 FOUNDATION_EXPORT double SwiftWarplyFrameworkVersionNumber;
...@@ -15,5 +14,3 @@ FOUNDATION_EXPORT double SwiftWarplyFrameworkVersionNumber; ...@@ -15,5 +14,3 @@ FOUNDATION_EXPORT double SwiftWarplyFrameworkVersionNumber;
15 FOUNDATION_EXPORT const unsigned char SwiftWarplyFrameworkVersionString[]; 14 FOUNDATION_EXPORT const unsigned char SwiftWarplyFrameworkVersionString[];
16 15
17 // In this header, you should import all the public headers of your framework using statements like #import <SwiftWarplyFramework/PublicHeader.h> 16 // In this header, you should import all the public headers of your framework using statements like #import <SwiftWarplyFramework/PublicHeader.h>
18 -
19 -
......
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 -//#define VERIFY_URL @"/partners/cosmote/verify"
32 -extern NSString* WARP_PRODUCTION_BASE_URL;
33 -extern NSString* WARP_HOST;
34 -extern NSString* WARP_ERROR_DOMAIN;
35 -extern NSString* MERCHANT_ID;
36 -extern NSString* LANG;
37 -extern NSString* VERIFY_URL;
38 -#define WARP_PAGE_URL_FORMAT @"%@/api/session/%@"
39 -#define WARP_IMAGE_URL_FORMAT @"%@/api/session/logo/%@"
40 -
41 -///////////////////////////////////////////////////////////////////////////////
42 -// Settings
43 -#ifdef _WL_VERSION
44 -#define WL_VERSION @ _WL_VERSION
45 -#else
46 -#define WL_VERSION @ "3.2.0a"
47 -#endif
48 -
49 -#define GEOFENCING_POIS_ENABLED @"GEOFENCING_POIS_ENABLED"
50 -#define WL_IOS_LOCATION_FOREGROUND_MODE @"IOS_LOCATION_FOREGROUND_MODE"
51 -#define WL_IOS_LOCATION_BACKGROUND_MODE @"IOS_LOCATION_BACKGROUND_MODE"
52 -#define WL_IOS_GEOFENCING_ENABLED @"IOS_GEOFENCING_ENABLED"
53 -#define WL_IOS_FOREGROUND_DISTANCE_FILTER @"IOS_FOREGROUND_DISTANCE_FILTER"
54 -#define WL_IOS_BACKGROUND_DISTANCE_FILTER @"IOS_BACKGROUND_DISTANCE_FILTER"
55 -#define WL_DEVICE_INFO_ENABLED @"DEVICE_INFO_ENABLED"
56 -#define WL_OFFERS_ENABLED @"OFFERS_ENABLED"
57 -#define WL_CONSUMER_DATA_ENABLED @"CONSUMER_DATA_ENABLED"
58 -#define WL_USER_SESSION_ENABLED @"USER_SESSION_ENABLED"
59 -#define WL_CUSTOM_ANALYTICS_ENABLED @"CUSTOM_ANALYTICS_ENABLED"
60 -#define WL_USER_TAGGING_ENABLED @"USER_TAGGING_ENABLED"
61 -#define WL_APPLICATION_DATA_ENABLED @"APPLICATION_DATA_ENABLED"
62 -#define WL_WARPLY_ENABLED @"WARPLY_ENABLED"
63 -#define WL_FEATURES_CHECK_INTERVAL @"FEATURES_CHECK_INTERVAL"
64 -#define WL_LIFECYCLE_ANALYTICS_ENABLED @"LIFECYCLE_ANALYTICS_ENABLED"
65 -#define WL_IOS_LOCATION_FOREGROUND_DESIRED_ACCURACY @"IOS_LOCATION_FOREGROUND_DESIRED_ACCURACY"
66 -#define WL_IOS_LOCATION_BACKGROUND_DESIRED_ACCURACY @"IOS_LOCATION_BACKGROUND_DESIRED_ACCURACY"
67 -#define WL_IOS_DEVICE_IS_WARPED @"is_warped"
68 -#define WL_IOS_DEVICE_HAS_DEVICE_INFO @"has_device_info"
69 -#define WL_IOS_DEVICE_HAS_APPLICATION_INFO @"has_application_info"
70 -#define WL_FEATURE_IS_DISABLED_WITH_KEY(KEY) \
71 - ([[NSUserDefaults standardUserDefaults] boolForKey:KEY] == NO \
72 - && [[NSUserDefaults standardUserDefaults] objectForKey:KEY] != nil) \
73 -
74 -#define WL_WARP_NOTIFICATIONS_ENABLED @"warp_enabled"
75 -#define WL_APPLICATION_DATA @"application_data"
76 -#define WL_DEVICE_STATUS @"device_status"
77 -#define WL_BEACON_ENABLED @"BEACON_ENABLED"
78 -#define WL_BEACON_TIME_INTERVAL_TO_RESEND @"BEACON_TIME_INTERVAL_TO_RESEND"
79 -#define WL_AUTHENTICATION @"AUTHENTICATION"
80 -#define WL_IS_JWT_ENABLED @"isJWTEnabled"
81 -
82 -///////////////////////////////////////////////////////////////////////////////
83 -// Logging
84 -#ifdef DEBUG
85 -#define WLLOG(xx, ...) NSLog(@"%s(%d): " xx, __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)
86 -#else
87 -#define WLLOG(xx, ...) ((void)0)
88 -#endif // #ifdef DEBUG
89 -
90 -///////////////////////////////////////////////////////////////////////////////
91 -// Version Interface
92 -#define WL_VERSION_INTERFACE() \
93 -+ (NSString *)get;
94 -
95 -#define WL_VERSION_IMPLEMENTATION(VERSION_STR) \
96 -+ (NSString *)get { \
97 - return VERSION_STR; \
98 -} \
99 -
100 -///////////////////////////////////////////////////////////////////////////////
101 -// System Versioning
102 -#define SYSTEM_VERSION_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
103 -#define SYSTEM_VERSION_GREATER_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
104 -#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
105 -#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
106 -#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)
107 -
108 -///////////////////////////////////////////////////////////////////////////////
109 -// Enum Versioning
110 -#ifdef __IPHONE_6_0 // iOS6 and later
111 -# define WLTextAlignmentCenter NSTextAlignmentCenter
112 -# define WLTextAlignmentLeft NSTextAlignmentLeft
113 -# define WLTextAlignmentRight NSTextAlignmentRight
114 -# define WLTextTruncationTail NSLineBreakByTruncatingTail
115 -# define WLTextTruncationMiddle NSLineBreakByWordWrapping
116 -# define WLLineBreakByWordWrapping NSLineBreakByWordWrapping
117 -#else // older versions
118 -# define WLTextAlignmentCenter UITextAlignmentCenter
119 -# define WLTextAlignmentLeft UITextAlignmentLeft
120 -# define WLTextAlignmentRight UITextAlignmentRight
121 -# define WLTextTruncationTail UILineBreakModeTailTruncation
122 -# define WLTextTruncationMiddle UILineBreakModeMiddleTruncation
123 -# define WLLineBreakByWordWrapping UILineBreakModeWordWrap
124 -#endif
This diff could not be displayed because it is too large.
1 -/*
2 - Copyright 2010-2016 Warply Inc. All rights reserved.
3 -
4 - Redistribution and use in source and binary forms, without modification,
5 - are permitted provided that the following conditions are met:
6 -
7 - 1. Redistributions of source code must retain the above copyright notice, this
8 - list of conditions and the following disclaimer.
9 -
10 - 2. Redistributions in binaryform must reproduce the above copyright notice,
11 - this list of conditions and the following disclaimer in the documentation
12 - and/or other materials provided with the distribution.
13 -
14 - THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 - IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 - MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 - EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 - INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 - BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 - OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 - */
25 -
26 -#import <Foundation/Foundation.h>
27 -#import <StoreKit/StoreKit.h>
28 -#import "Warply.h"
29 -
30 -@interface WLAPPActionHandler : NSObject <WLActionHandler,SKStoreProductViewControllerDelegate>
31 -
32 -@end
1 -/*
2 - Copyright 2010-2016 Warply Inc. All rights reserved.
3 -
4 - Redistribution and use in source and binary forms, without modification,
5 - are permitted provided that the following conditions are met:
6 -
7 - 1. Redistributions of source code must retain the above copyright notice, this
8 - list of conditions and the following disclaimer.
9 -
10 - 2. Redistributions in binaryform must reproduce the above copyright notice,
11 - this list of conditions and the following disclaimer in the documentation
12 - and/or other materials provided with the distribution.
13 -
14 - THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 - IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 - MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 - EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 - INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 - BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 - OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 - */
25 -
26 -#import "WLAPPActionHandler.h"
27 -#import "WLAnalyticsManager.h"
28 -#import "WLInboxItemViewController.h"
29 -#import "NSString+SSToolkitAdditions.h"
30 -#import "UIViewController+WLAdditions.h"
31 -
32 -@interface WLAPPActionHandler ()
33 -
34 -@property (nonatomic, assign) WLInboxItemViewController *inboxVC;
35 -@property (nonatomic) BOOL *loadingProduct;
36 -@end
37 -
38 -
39 -@implementation WLAPPActionHandler
40 -
41 -#pragma mark - Static Methods
42 -////////////////////////////////////////////////////////////////////////////////
43 -- (BOOL)canHandleActionUrl:(NSURL *)url
44 -{
45 - return [url.scheme isEqualToString: @"itms-apps"];
46 -}
47 -
48 -#pragma mark - Override Methods
49 -////////////////////////////////////////////////////////////////////////////////
50 -- (void)handleActionUrl:(NSURL *)url
51 -{
52 - UINavigationController *inboxNavCon = (UINavigationController *)[([UIApplication sharedApplication].delegate).window.rootViewController topModalViewController];
53 - self.inboxVC = [inboxNavCon.viewControllers objectAtIndex:0];
54 -
55 - NSString *appID = nil;
56 -
57 - if ([SKStoreProductViewController class]) {
58 - __block SKStoreProductViewController *storeViewController = [[SKStoreProductViewController alloc] init];
59 - storeViewController.delegate = self;
60 - NSString *escapedResourceSpecifier = [url.resourceSpecifier stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
61 - NSRange appIDRange = [escapedResourceSpecifier rangeOfString:@"id"];
62 - NSRange appQuestionMarkRange = [escapedResourceSpecifier rangeOfString:@"?"];
63 -
64 - if (appIDRange.location != NSNotFound && appQuestionMarkRange.location != NSNotFound) {
65 - appID = [escapedResourceSpecifier substringWithRange:NSMakeRange(appIDRange.location + 2, appQuestionMarkRange.location - (appIDRange.location + 2))];
66 - }
67 -
68 - NSDictionary *parameters = @{SKStoreProductParameterITunesItemIdentifier:[NSNumber numberWithInteger:[appID intValue]]};
69 - [storeViewController loadProductWithParameters:parameters
70 - completionBlock:^(BOOL result, NSError *error) {
71 - if (result) {
72 - [self.inboxVC presentViewController:storeViewController animated:YES completion:nil];
73 - }
74 - }];
75 - } else {
76 - [[UIApplication sharedApplication] openURL:url];
77 - }
78 -
79 - [WLAnalyticsManager logUrgentEventWithEventId:@"NB_CUSTOM_ACTION" pageId:@"APP_DOWNLOAD" actionMetadata:@{@"result":@[@"APPSTORE"], @"session_uuid":self.inboxVC.session_uuid, @"url": [url absoluteString]}];
80 -}
81 -
82 -#pragma mark - SKStoreProductViewControllerDelegate
83 -////////////////////////////////////////////////////////////////////////////////
84 --(void)productViewControllerDidFinish:(SKStoreProductViewController *)viewController
85 -{
86 - [viewController dismissViewControllerAnimated:YES completion:nil];
87 -}
88 -
89 -@end
1 -/*
2 - Copyright 2010-2016 Warply Inc. All rights reserved.
3 -
4 - Redistribution and use in source and binary forms, without modification,
5 - are permitted provided that the following conditions are met:
6 -
7 - 1. Redistributions of source code must retain the above copyright notice, this
8 - list of conditions and the following disclaimer.
9 -
10 - 2. Redistributions in binaryform must reproduce the above copyright notice,
11 - this list of conditions and the following disclaimer in the documentation
12 - and/or other materials provided with the distribution.
13 -
14 - THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 - IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 - MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 - EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 - INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 - BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 - OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 - */
25 -
26 -#import <MessageUI/MessageUI.h>
27 -#import "Warply.h"
28 -
29 -@interface WLSMSActionHandlerDeprecated : NSObject <MFMessageComposeViewControllerDelegate, WLActionHandler>
30 -
31 -@end
1 -/*
2 - Copyright 2010-2016 Warply Inc. All rights reserved.
3 -
4 - Redistribution and use in source and binary forms, without modification,
5 - are permitted provided that the following conditions are met:
6 -
7 - 1. Redistributions of source code must retain the above copyright notice, this
8 - list of conditions and the following disclaimer.
9 -
10 - 2. Redistributions in binaryform must reproduce the above copyright notice,
11 - this list of conditions and the following disclaimer in the documentation
12 - and/or other materials provided with the distribution.
13 -
14 - THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 - IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 - MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 - EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 - INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 - BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 - OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 - */
25 -
26 -#import "WLSMSActionHandlerDeprecated.h"
27 -#import "WLGlobals.h"
28 -#import "WLInboxItemViewController.h"
29 -#import "UIViewController+WLAdditions.h"
30 -
31 -@interface WLSMSActionHandlerDeprecated ()
32 -@property (nonatomic , weak) WLInboxItemViewController *inboxVC;
33 -@end
34 -
35 -@implementation WLSMSActionHandlerDeprecated
36 -
37 -#pragma mark - Static Methods
38 -///////////////////////////////////////////////////////////////////////////////////////////////////
39 -- (BOOL)canHandleActionUrl:(NSURL *)url
40 -{
41 - return [[url scheme] isEqualToString: @"rsms"];
42 -}
43 -
44 -#pragma mark - Override Methods
45 -///////////////////////////////////////////////////////////////////////////////////////////////////
46 -- (void)handleActionUrl:(NSURL *)url
47 -{
48 - self.inboxVC = (WLInboxItemViewController *)[([UIApplication sharedApplication].delegate).window.rootViewController topModalViewController];
49 -
50 -
51 - NSArray *args = [url.resourceSpecifier componentsSeparatedByString:@"/"];
52 - if (args == nil)
53 - return;
54 -
55 - if ([args count] < 4)
56 - return;
57 -
58 - MFMessageComposeViewController *smsController = [[MFMessageComposeViewController alloc] init];
59 - @try {
60 - [smsController setRecipients:[NSArray arrayWithObject:[args objectAtIndex:4]]];
61 - //[smsController setBody:[NSString stringWithFormat:@"Hello from %@", BRAND_NAME]];
62 -
63 - if ([args count] > 4) {
64 - NSString *body = [[args objectAtIndex:5] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
65 - [smsController setBody:body];
66 - }
67 -
68 - [smsController setMessageComposeDelegate:self];
69 - [_inboxVC presentViewController:smsController animated:YES completion:nil];
70 - }
71 - @finally {
72 -
73 - }
74 -}
75 -
76 -#pragma mark - MFMessageComposeViewControllerDelegate
77 -///////////////////////////////////////////////////////////////////////////////////////////////////
78 -- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
79 -{
80 - WLInboxItemViewController *inboxItemViewController = (WLInboxItemViewController *)[([UIApplication sharedApplication].delegate).window.rootViewController topModalViewController];
81 - NSString *resultString;
82 - switch (result) {
83 - case MessageComposeResultCancelled:
84 - resultString = @"sms_cancelled";
85 - break;
86 - case MessageComposeResultFailed:
87 - resultString = @"sms_failed";
88 - break;
89 - case MessageComposeResultSent:
90 - resultString = @"sms_sent";
91 - }
92 - [WLAnalyticsManager logEventWithEventId:@"NB_ACTION" pageId:inboxItemViewController.session_uuid actionMetadata:[NSDictionary dictionaryWithObjectsAndKeys:resultString, @"sms_result", self.inboxVC.requestedUrl.absoluteString, @"action_url", nil]];
93 - [controller dismissViewControllerAnimated:YES completion:nil];
94 -}
95 -
96 -@end
1 -/*
2 - Copyright 2010-2016 Warply Inc. All rights reserved.
3 -
4 - Redistribution and use in source and binary forms, without modification,
5 - are permitted provided that the following conditions are met:
6 -
7 - 1. Redistributions of source code must retain the above copyright notice, this
8 - list of conditions and the following disclaimer.
9 -
10 - 2. Redistributions in binaryform must reproduce the above copyright notice,
11 - this list of conditions and the following disclaimer in the documentation
12 - and/or other materials provided with the distribution.
13 -
14 - THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 - IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 - MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 - EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 - INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 - BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 - OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 - */
25 -
26 -#import <MessageUI/MessageUI.h>
27 -#import "Warply.h"
28 -
29 -@interface WLSMSActionHanlder : NSObject <MFMessageComposeViewControllerDelegate, WLActionHandler>
30 -
31 -@end
...\ No newline at end of file ...\ No newline at end of file
1 -/*
2 - Copyright 2010-2016 Warply Inc. All rights reserved.
3 -
4 - Redistribution and use in source and binary forms, without modification,
5 - are permitted provided that the following conditions are met:
6 -
7 - 1. Redistributions of source code must retain the above copyright notice, this
8 - list of conditions and the following disclaimer.
9 -
10 - 2. Redistributions in binaryform must reproduce the above copyright notice,
11 - this list of conditions and the following disclaimer in the documentation
12 - and/or other materials provided with the distribution.
13 -
14 - THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
15 - IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
16 - MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
17 - EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 - INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
19 - BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
22 - OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
23 - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 - */
25 -
26 -#import "WLSMSActionHanlder.h"
27 -#import "WLGlobals.h"
28 -#import "WLAnalyticsManager.h"
29 -#import "WLInboxItemViewController.h"
30 -#import "WLBaseItem.h"
31 -#import "UIViewController+WLAdditions.h"
32 -
33 -@interface WLSMSActionHanlder ()
34 -
35 -@property (nonatomic, weak) WLInboxItemViewController *inboxVC;
36 -
37 -@end
38 -
39 -@implementation WLSMSActionHanlder
40 -
41 -#pragma mark - Static Methods
42 -///////////////////////////////////////////////////////////////////////////////////////////////////
43 -- (BOOL)canHandleActionUrl:(NSURL *)url
44 -{
45 - return [url.scheme isEqualToString: @"sms"];
46 -}
47 -
48 -#pragma mark - Override Methods
49 -///////////////////////////////////////////////////////////////////////////////////////////////////
50 -- (void)handleActionUrl:(NSURL *)url
51 -{
52 - UINavigationController *inboxNavCon = (UINavigationController *)[([UIApplication sharedApplication].delegate).window.rootViewController topModalViewController];
53 - self.inboxVC = [inboxNavCon.viewControllers objectAtIndex:0];
54 -
55 - if (![MFMessageComposeViewController canSendText]) {
56 - UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"This device does not support text messages", @"Warply") message:nil delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", @"Warply") otherButtonTitles:nil];
57 - [alert show];
58 -
59 - return;
60 - }
61 -
62 - WLLOG(@"SMS URI: %@", url.absoluteString);
63 - if (url.resourceSpecifier == nil) {
64 - return;
65 - }
66 - NSString *escapedResourceSpecifier = [url.resourceSpecifier stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
67 - NSArray *args = [escapedResourceSpecifier componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"?&"]];
68 - NSString *recipientsString = [args objectAtIndex:0];
69 - NSArray *recipients = [recipientsString componentsSeparatedByString:@","];
70 - NSString *bodyString = nil;
71 -
72 - for (NSString *argument in args) {
73 - if ([argument isEqualToString:recipientsString]) {
74 - continue;
75 - }
76 - NSRange bodyKeyRange = [argument rangeOfString:@"body="];
77 - if (bodyKeyRange.location != NSNotFound) {
78 - bodyString = [argument substringFromIndex:bodyKeyRange.length];
79 - }
80 - }
81 -
82 - MFMessageComposeViewController *smsController = [[MFMessageComposeViewController alloc] init];
83 - [smsController setRecipients:recipients];
84 - [smsController setBody:bodyString];
85 -
86 - [smsController setMessageComposeDelegate:self];
87 - [_inboxVC presentViewController:smsController animated:YES completion:nil];
88 -
89 -}
90 -
91 -#pragma mark - MFMessageComposeViewControllerDelegate
92 -///////////////////////////////////////////////////////////////////////////////////////////////////
93 -- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
94 -{
95 - NSArray *results;
96 - switch (result) {
97 - case MessageComposeResultCancelled:
98 - results = @[@"sms_prompt_clicked", @"sms_cancelled"];
99 - break;
100 - case MessageComposeResultFailed:
101 - results = @[@"sms_prompt_clicked", @"sms_failed"];
102 - break;
103 - case MessageComposeResultSent:
104 - results = @[@"sms_prompt_clicked", @"sms_sent"];
105 - }
106 - [WLAnalyticsManager logUrgentEventWithEventId:@"NB_CUSTOM_ACTION" pageId:@"SMS" actionMetadata:@{@"session_uuid": self.inboxVC.session_uuid, @"result":results}];
107 - [controller dismissViewControllerAnimated:YES completion:nil];
108 -}
109 -
110 -@end
1 -// AFNetworkReachabilityManager.h
2 -// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 -//
4 -// Permission is hereby granted, free of charge, to any person obtaining a copy
5 -// of this software and associated documentation files (the "Software"), to deal
6 -// in the Software without restriction, including without limitation the rights
7 -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 -// copies of the Software, and to permit persons to whom the Software is
9 -// furnished to do so, subject to the following conditions:
10 -//
11 -// The above copyright notice and this permission notice shall be included in
12 -// all copies or substantial portions of the Software.
13 -//
14 -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 -// THE SOFTWARE.
21 -
22 -#import <Foundation/Foundation.h>
23 -
24 -#if !TARGET_OS_WATCH
25 -#import <SystemConfiguration/SystemConfiguration.h>
26 -
27 -typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
28 - AFNetworkReachabilityStatusUnknown = -1,
29 - AFNetworkReachabilityStatusNotReachable = 0,
30 - AFNetworkReachabilityStatusReachableViaWWAN = 1,
31 - AFNetworkReachabilityStatusReachableViaWiFi = 2,
32 -};
33 -
34 -NS_ASSUME_NONNULL_BEGIN
35 -
36 -/**
37 - `AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces.
38 -
39 - Reachability can be used to determine background information about why a network operation failed, or to trigger a network operation retrying when a connection is established. It should not be used to prevent a user from initiating a network request, as it's possible that an initial request may be required to establish reachability.
40 -
41 - See Apple's Reachability Sample Code ( https://developer.apple.com/library/ios/samplecode/reachability/ )
42 -
43 - @warning Instances of `AFNetworkReachabilityManager` must be started with `-startMonitoring` before reachability status can be determined.
44 - */
45 -@interface AFNetworkReachabilityManager : NSObject
46 -
47 -/**
48 - The current network reachability status.
49 - */
50 -@property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;
51 -
52 -/**
53 - Whether or not the network is currently reachable.
54 - */
55 -@property (readonly, nonatomic, assign, getter = isReachable) BOOL reachable;
56 -
57 -/**
58 - Whether or not the network is currently reachable via WWAN.
59 - */
60 -@property (readonly, nonatomic, assign, getter = isReachableViaWWAN) BOOL reachableViaWWAN;
61 -
62 -/**
63 - Whether or not the network is currently reachable via WiFi.
64 - */
65 -@property (readonly, nonatomic, assign, getter = isReachableViaWiFi) BOOL reachableViaWiFi;
66 -
67 -///---------------------
68 -/// @name Initialization
69 -///---------------------
70 -
71 -/**
72 - Returns the shared network reachability manager.
73 - */
74 -+ (instancetype)sharedManager;
75 -
76 -/**
77 - Creates and returns a network reachability manager with the default socket address.
78 -
79 - @return An initialized network reachability manager, actively monitoring the default socket address.
80 - */
81 -+ (instancetype)manager;
82 -
83 -/**
84 - Creates and returns a network reachability manager for the specified domain.
85 -
86 - @param domain The domain used to evaluate network reachability.
87 -
88 - @return An initialized network reachability manager, actively monitoring the specified domain.
89 - */
90 -+ (instancetype)managerForDomain:(NSString *)domain;
91 -
92 -/**
93 - Creates and returns a network reachability manager for the socket address.
94 -
95 - @param address The socket address (`sockaddr_in6`) used to evaluate network reachability.
96 -
97 - @return An initialized network reachability manager, actively monitoring the specified socket address.
98 - */
99 -+ (instancetype)managerForAddress:(const void *)address;
100 -
101 -/**
102 - Initializes an instance of a network reachability manager from the specified reachability object.
103 -
104 - @param reachability The reachability object to monitor.
105 -
106 - @return An initialized network reachability manager, actively monitoring the specified reachability.
107 - */
108 -- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability NS_DESIGNATED_INITIALIZER;
109 -
110 -/**
111 - * Initializes an instance of a network reachability manager
112 - *
113 - * @return nil as this method is unavailable
114 - */
115 -- (nullable instancetype)init NS_UNAVAILABLE;
116 -
117 -///--------------------------------------------------
118 -/// @name Starting & Stopping Reachability Monitoring
119 -///--------------------------------------------------
120 -
121 -/**
122 - Starts monitoring for changes in network reachability status.
123 - */
124 -- (void)startMonitoring;
125 -
126 -/**
127 - Stops monitoring for changes in network reachability status.
128 - */
129 -- (void)stopMonitoring;
130 -
131 -///-------------------------------------------------
132 -/// @name Getting Localized Reachability Description
133 -///-------------------------------------------------
134 -
135 -/**
136 - Returns a localized string representation of the current network reachability status.
137 - */
138 -- (NSString *)localizedNetworkReachabilityStatusString;
139 -
140 -///---------------------------------------------------
141 -/// @name Setting Network Reachability Change Callback
142 -///---------------------------------------------------
143 -
144 -/**
145 - Sets a callback to be executed when the network availability of the `baseURL` host changes.
146 -
147 - @param block A block object to be executed when the network availability of the `baseURL` host changes.. This block has no return value and takes a single argument which represents the various reachability states from the device to the `baseURL`.
148 - */
149 -- (void)setReachabilityStatusChangeBlock:(nullable void (^)(AFNetworkReachabilityStatus status))block;
150 -
151 -@end
152 -
153 -///----------------
154 -/// @name Constants
155 -///----------------
156 -
157 -/**
158 - ## Network Reachability
159 -
160 - The following constants are provided by `AFNetworkReachabilityManager` as possible network reachability statuses.
161 -
162 - enum {
163 - AFNetworkReachabilityStatusUnknown,
164 - AFNetworkReachabilityStatusNotReachable,
165 - AFNetworkReachabilityStatusReachableViaWWAN,
166 - AFNetworkReachabilityStatusReachableViaWiFi,
167 - }
168 -
169 - `AFNetworkReachabilityStatusUnknown`
170 - The `baseURL` host reachability is not known.
171 -
172 - `AFNetworkReachabilityStatusNotReachable`
173 - The `baseURL` host cannot be reached.
174 -
175 - `AFNetworkReachabilityStatusReachableViaWWAN`
176 - The `baseURL` host can be reached via a cellular connection, such as EDGE or GPRS.
177 -
178 - `AFNetworkReachabilityStatusReachableViaWiFi`
179 - The `baseURL` host can be reached via a Wi-Fi connection.
180 -
181 - ### Keys for Notification UserInfo Dictionary
182 -
183 - Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification.
184 -
185 - `AFNetworkingReachabilityNotificationStatusItem`
186 - A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification.
187 - The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status.
188 - */
189 -
190 -///--------------------
191 -/// @name Notifications
192 -///--------------------
193 -
194 -/**
195 - Posted when network reachability changes.
196 - This notification assigns no notification object. The `userInfo` dictionary contains an `NSNumber` object under the `AFNetworkingReachabilityNotificationStatusItem` key, representing the `AFNetworkReachabilityStatus` value for the current network reachability.
197 -
198 - @warning In order for network reachability to be monitored, include the `SystemConfiguration` framework in the active target's "Link Binary With Library" build phase, and add `#import <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (`Prefix.pch`).
199 - */
200 -FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityDidChangeNotification;
201 -FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityNotificationStatusItem;
202 -
203 -///--------------------
204 -/// @name Functions
205 -///--------------------
206 -
207 -/**
208 - Returns a localized string representation of an `AFNetworkReachabilityStatus` value.
209 - */
210 -FOUNDATION_EXPORT NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status);
211 -
212 -NS_ASSUME_NONNULL_END
213 -#endif
1 -// AFNetworkReachabilityManager.m
2 -// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 -//
4 -// Permission is hereby granted, free of charge, to any person obtaining a copy
5 -// of this software and associated documentation files (the "Software"), to deal
6 -// in the Software without restriction, including without limitation the rights
7 -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 -// copies of the Software, and to permit persons to whom the Software is
9 -// furnished to do so, subject to the following conditions:
10 -//
11 -// The above copyright notice and this permission notice shall be included in
12 -// all copies or substantial portions of the Software.
13 -//
14 -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 -// THE SOFTWARE.
21 -
22 -#import "AFNetworkReachabilityManager.h"
23 -#if !TARGET_OS_WATCH
24 -
25 -#import <netinet/in.h>
26 -#import <netinet6/in6.h>
27 -#import <arpa/inet.h>
28 -#import <ifaddrs.h>
29 -#import <netdb.h>
30 -
31 -NSString * const AFNetworkingReachabilityDidChangeNotification = @"com.alamofire.networking.reachability.change";
32 -NSString * const AFNetworkingReachabilityNotificationStatusItem = @"AFNetworkingReachabilityNotificationStatusItem";
33 -
34 -typedef void (^AFNetworkReachabilityStatusBlock)(AFNetworkReachabilityStatus status);
35 -
36 -NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status) {
37 - switch (status) {
38 - case AFNetworkReachabilityStatusNotReachable:
39 - return NSLocalizedStringFromTable(@"Not Reachable", @"AFNetworking", nil);
40 - case AFNetworkReachabilityStatusReachableViaWWAN:
41 - return NSLocalizedStringFromTable(@"Reachable via WWAN", @"AFNetworking", nil);
42 - case AFNetworkReachabilityStatusReachableViaWiFi:
43 - return NSLocalizedStringFromTable(@"Reachable via WiFi", @"AFNetworking", nil);
44 - case AFNetworkReachabilityStatusUnknown:
45 - default:
46 - return NSLocalizedStringFromTable(@"Unknown", @"AFNetworking", nil);
47 - }
48 -}
49 -
50 -static AFNetworkReachabilityStatus AFNetworkReachabilityStatusForFlags(SCNetworkReachabilityFlags flags) {
51 - BOOL isReachable = ((flags & kSCNetworkReachabilityFlagsReachable) != 0);
52 - BOOL needsConnection = ((flags & kSCNetworkReachabilityFlagsConnectionRequired) != 0);
53 - BOOL canConnectionAutomatically = (((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) || ((flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0));
54 - BOOL canConnectWithoutUserInteraction = (canConnectionAutomatically && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0);
55 - BOOL isNetworkReachable = (isReachable && (!needsConnection || canConnectWithoutUserInteraction));
56 -
57 - AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusUnknown;
58 - if (isNetworkReachable == NO) {
59 - status = AFNetworkReachabilityStatusNotReachable;
60 - }
61 -#if TARGET_OS_IPHONE
62 - else if ((flags & kSCNetworkReachabilityFlagsIsWWAN) != 0) {
63 - status = AFNetworkReachabilityStatusReachableViaWWAN;
64 - }
65 -#endif
66 - else {
67 - status = AFNetworkReachabilityStatusReachableViaWiFi;
68 - }
69 -
70 - return status;
71 -}
72 -
73 -/**
74 - * Queue a status change notification for the main thread.
75 - *
76 - * This is done to ensure that the notifications are received in the same order
77 - * as they are sent. If notifications are sent directly, it is possible that
78 - * a queued notification (for an earlier status condition) is processed after
79 - * the later update, resulting in the listener being left in the wrong state.
80 - */
81 -static void AFPostReachabilityStatusChange(SCNetworkReachabilityFlags flags, AFNetworkReachabilityStatusBlock block) {
82 - AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags);
83 - dispatch_async(dispatch_get_main_queue(), ^{
84 - if (block) {
85 - block(status);
86 - }
87 - NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
88 - NSDictionary *userInfo = @{ AFNetworkingReachabilityNotificationStatusItem: @(status) };
89 - [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:userInfo];
90 - });
91 -}
92 -
93 -static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) {
94 - AFPostReachabilityStatusChange(flags, (__bridge AFNetworkReachabilityStatusBlock)info);
95 -}
96 -
97 -
98 -static const void * AFNetworkReachabilityRetainCallback(const void *info) {
99 - return Block_copy(info);
100 -}
101 -
102 -static void AFNetworkReachabilityReleaseCallback(const void *info) {
103 - if (info) {
104 - Block_release(info);
105 - }
106 -}
107 -
108 -@interface AFNetworkReachabilityManager ()
109 -@property (readonly, nonatomic, assign) SCNetworkReachabilityRef networkReachability;
110 -@property (readwrite, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;
111 -@property (readwrite, nonatomic, copy) AFNetworkReachabilityStatusBlock networkReachabilityStatusBlock;
112 -@end
113 -
114 -@implementation AFNetworkReachabilityManager
115 -
116 -+ (instancetype)sharedManager {
117 - static AFNetworkReachabilityManager *_sharedManager = nil;
118 - static dispatch_once_t onceToken;
119 - dispatch_once(&onceToken, ^{
120 - _sharedManager = [self manager];
121 - });
122 -
123 - return _sharedManager;
124 -}
125 -
126 -+ (instancetype)managerForDomain:(NSString *)domain {
127 - SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [domain UTF8String]);
128 -
129 - AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability];
130 -
131 - CFRelease(reachability);
132 -
133 - return manager;
134 -}
135 -
136 -+ (instancetype)managerForAddress:(const void *)address {
137 - SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)address);
138 - AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability];
139 -
140 - CFRelease(reachability);
141 -
142 - return manager;
143 -}
144 -
145 -+ (instancetype)manager
146 -{
147 -#if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 90000) || (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101100)
148 - struct sockaddr_in6 address;
149 - bzero(&address, sizeof(address));
150 - address.sin6_len = sizeof(address);
151 - address.sin6_family = AF_INET6;
152 -#else
153 - struct sockaddr_in address;
154 - bzero(&address, sizeof(address));
155 - address.sin_len = sizeof(address);
156 - address.sin_family = AF_INET;
157 -#endif
158 - return [self managerForAddress:&address];
159 -}
160 -
161 -- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability {
162 - self = [super init];
163 - if (!self) {
164 - return nil;
165 - }
166 -
167 - _networkReachability = CFRetain(reachability);
168 - self.networkReachabilityStatus = AFNetworkReachabilityStatusUnknown;
169 -
170 - return self;
171 -}
172 -
173 -- (instancetype)init NS_UNAVAILABLE
174 -{
175 - return nil;
176 -}
177 -
178 -- (void)dealloc {
179 - [self stopMonitoring];
180 -
181 - if (_networkReachability != NULL) {
182 - CFRelease(_networkReachability);
183 - }
184 -}
185 -
186 -#pragma mark -
187 -
188 -- (BOOL)isReachable {
189 - return [self isReachableViaWWAN] || [self isReachableViaWiFi];
190 -}
191 -
192 -- (BOOL)isReachableViaWWAN {
193 - return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN;
194 -}
195 -
196 -- (BOOL)isReachableViaWiFi {
197 - return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi;
198 -}
199 -
200 -#pragma mark -
201 -
202 -- (void)startMonitoring {
203 - [self stopMonitoring];
204 -
205 - if (!self.networkReachability) {
206 - return;
207 - }
208 -
209 - __weak __typeof(self)weakSelf = self;
210 - AFNetworkReachabilityStatusBlock callback = ^(AFNetworkReachabilityStatus status) {
211 - __strong __typeof(weakSelf)strongSelf = weakSelf;
212 -
213 - strongSelf.networkReachabilityStatus = status;
214 - if (strongSelf.networkReachabilityStatusBlock) {
215 - strongSelf.networkReachabilityStatusBlock(status);
216 - }
217 -
218 - };
219 -
220 - SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL};
221 - SCNetworkReachabilitySetCallback(self.networkReachability, AFNetworkReachabilityCallback, &context);
222 - SCNetworkReachabilityScheduleWithRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes);
223 -
224 - dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^{
225 - SCNetworkReachabilityFlags flags;
226 - if (SCNetworkReachabilityGetFlags(self.networkReachability, &flags)) {
227 - AFPostReachabilityStatusChange(flags, callback);
228 - }
229 - });
230 -}
231 -
232 -- (void)stopMonitoring {
233 - if (!self.networkReachability) {
234 - return;
235 - }
236 -
237 - SCNetworkReachabilityUnscheduleFromRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes);
238 -}
239 -
240 -#pragma mark -
241 -
242 -- (NSString *)localizedNetworkReachabilityStatusString {
243 - return AFStringFromNetworkReachabilityStatus(self.networkReachabilityStatus);
244 -}
245 -
246 -#pragma mark -
247 -
248 -- (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block {
249 - self.networkReachabilityStatusBlock = block;
250 -}
251 -
252 -#pragma mark - NSKeyValueObserving
253 -
254 -+ (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key {
255 - if ([key isEqualToString:@"reachable"] || [key isEqualToString:@"reachableViaWWAN"] || [key isEqualToString:@"reachableViaWiFi"]) {
256 - return [NSSet setWithObject:@"networkReachabilityStatus"];
257 - }
258 -
259 - return [super keyPathsForValuesAffectingValueForKey:key];
260 -}
261 -
262 -@end
263 -#endif
1 -// AFNetworking.h
2 -//
3 -// Copyright (c) 2013 AFNetworking (http://afnetworking.com/)
4 -//
5 -// Permission is hereby granted, free of charge, to any person obtaining a copy
6 -// of this software and associated documentation files (the "Software"), to deal
7 -// in the Software without restriction, including without limitation the rights
8 -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 -// copies of the Software, and to permit persons to whom the Software is
10 -// furnished to do so, subject to the following conditions:
11 -//
12 -// The above copyright notice and this permission notice shall be included in
13 -// all copies or substantial portions of the Software.
14 -//
15 -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 -// THE SOFTWARE.
22 -
23 -#import <Foundation/Foundation.h>
24 -#import <Availability.h>
25 -#import <TargetConditionals.h>
26 -
27 -#ifndef _AFNETWORKING_
28 - #define _AFNETWORKING_
29 -
30 - #import "AFURLRequestSerialization.h"
31 - #import "AFURLResponseSerialization.h"
32 - #import "AFSecurityPolicy.h"
33 -
34 -#if !TARGET_OS_WATCH
35 - #import "AFNetworkReachabilityManager.h"
36 -#endif
37 -
38 - #import "AFURLSessionManager.h"
39 - #import "AFHTTPSessionManager.h"
40 -
41 -#endif /* _AFNETWORKING_ */
1 -// AFSecurityPolicy.h
2 -// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 -//
4 -// Permission is hereby granted, free of charge, to any person obtaining a copy
5 -// of this software and associated documentation files (the "Software"), to deal
6 -// in the Software without restriction, including without limitation the rights
7 -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 -// copies of the Software, and to permit persons to whom the Software is
9 -// furnished to do so, subject to the following conditions:
10 -//
11 -// The above copyright notice and this permission notice shall be included in
12 -// all copies or substantial portions of the Software.
13 -//
14 -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 -// THE SOFTWARE.
21 -
22 -#import <Foundation/Foundation.h>
23 -#import <Security/Security.h>
24 -
25 -typedef NS_ENUM(NSUInteger, AFSSLPinningMode) {
26 - AFSSLPinningModeNone,
27 - AFSSLPinningModePublicKey,
28 - AFSSLPinningModeCertificate,
29 -};
30 -
31 -/**
32 - `AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections.
33 -
34 - Adding pinned SSL certificates to your app helps prevent man-in-the-middle attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with SSL pinning configured and enabled.
35 - */
36 -
37 -NS_ASSUME_NONNULL_BEGIN
38 -
39 -@interface AFSecurityPolicy : NSObject <NSSecureCoding, NSCopying>
40 -
41 -/**
42 - The criteria by which server trust should be evaluated against the pinned SSL certificates. Defaults to `AFSSLPinningModeNone`.
43 - */
44 -@property (readonly, nonatomic, assign) AFSSLPinningMode SSLPinningMode;
45 -
46 -/**
47 - The certificates used to evaluate server trust according to the SSL pinning mode.
48 -
49 - By default, this property is set to any (`.cer`) certificates included in the target compiling AFNetworking. Note that if you are using AFNetworking as embedded framework, no certificates will be pinned by default. Use `certificatesInBundle` to load certificates from your target, and then create a new policy by calling `policyWithPinningMode:withPinnedCertificates`.
50 -
51 - Note that if pinning is enabled, `evaluateServerTrust:forDomain:` will return true if any pinned certificate matches.
52 - */
53 -@property (nonatomic, strong, nullable) NSSet <NSData *> *pinnedCertificates;
54 -
55 -/**
56 - Whether or not to trust servers with an invalid or expired SSL certificates. Defaults to `NO`.
57 - */
58 -@property (nonatomic, assign) BOOL allowInvalidCertificates;
59 -
60 -/**
61 - Whether or not to validate the domain name in the certificate's CN field. Defaults to `YES`.
62 - */
63 -@property (nonatomic, assign) BOOL validatesDomainName;
64 -
65 -///-----------------------------------------
66 -/// @name Getting Certificates from the Bundle
67 -///-----------------------------------------
68 -
69 -/**
70 - Returns any certificates included in the bundle. If you are using AFNetworking as an embedded framework, you must use this method to find the certificates you have included in your app bundle, and use them when creating your security policy by calling `policyWithPinningMode:withPinnedCertificates`.
71 -
72 - @return The certificates included in the given bundle.
73 - */
74 -+ (NSSet <NSData *> *)certificatesInBundle:(NSBundle *)bundle;
75 -
76 -///-----------------------------------------
77 -/// @name Getting Specific Security Policies
78 -///-----------------------------------------
79 -
80 -/**
81 - Returns the shared default security policy, which does not allow invalid certificates, validates domain name, and does not validate against pinned certificates or public keys.
82 -
83 - @return The default security policy.
84 - */
85 -+ (instancetype)defaultPolicy;
86 -
87 -///---------------------
88 -/// @name Initialization
89 -///---------------------
90 -
91 -/**
92 - Creates and returns a security policy with the specified pinning mode.
93 -
94 - @param pinningMode The SSL pinning mode.
95 -
96 - @return A new security policy.
97 - */
98 -+ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode;
99 -
100 -/**
101 - Creates and returns a security policy with the specified pinning mode.
102 -
103 - @param pinningMode The SSL pinning mode.
104 - @param pinnedCertificates The certificates to pin against.
105 -
106 - @return A new security policy.
107 - */
108 -+ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet <NSData *> *)pinnedCertificates;
109 -
110 -///------------------------------
111 -/// @name Evaluating Server Trust
112 -///------------------------------
113 -
114 -/**
115 - Whether or not the specified server trust should be accepted, based on the security policy.
116 -
117 - This method should be used when responding to an authentication challenge from a server.
118 -
119 - @param serverTrust The X.509 certificate trust of the server.
120 - @param domain The domain of serverTrust. If `nil`, the domain will not be validated.
121 -
122 - @return Whether or not to trust the server.
123 - */
124 -- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust
125 - forDomain:(nullable NSString *)domain;
126 -
127 -@end
128 -
129 -NS_ASSUME_NONNULL_END
130 -
131 -///----------------
132 -/// @name Constants
133 -///----------------
134 -
135 -/**
136 - ## SSL Pinning Modes
137 -
138 - The following constants are provided by `AFSSLPinningMode` as possible SSL pinning modes.
139 -
140 - enum {
141 - AFSSLPinningModeNone,
142 - AFSSLPinningModePublicKey,
143 - AFSSLPinningModeCertificate,
144 - }
145 -
146 - `AFSSLPinningModeNone`
147 - Do not used pinned certificates to validate servers.
148 -
149 - `AFSSLPinningModePublicKey`
150 - Validate host certificates against public keys of pinned certificates.
151 -
152 - `AFSSLPinningModeCertificate`
153 - Validate host certificates against pinned certificates.
154 -*/
1 -// 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 "SwiftWarplyFramework/AFHTTPSessionManager.h"
29 -
30 -NS_ASSUME_NONNULL_BEGIN
31 -
32 -typedef NS_ENUM(NSInteger, AFImageDownloadPrioritization) {
33 - AFImageDownloadPrioritizationFIFO,
34 - AFImageDownloadPrioritizationLIFO
35 -};
36 -
37 -/**
38 - The `AFImageDownloadReceipt` is an object vended by the `AFImageDownloader` when starting a data task. It can be used to cancel active tasks running on the `AFImageDownloader` session. As a general rule, image data tasks should be cancelled using the `AFImageDownloadReceipt` instead of calling `cancel` directly on the `task` itself. The `AFImageDownloader` is optimized to handle duplicate task scenarios as well as pending versus active downloads.
39 - */
40 -@interface AFImageDownloadReceipt : NSObject
41 -
42 -/**
43 - The data task created by the `AFImageDownloader`.
44 -*/
45 -@property (nonatomic, strong) NSURLSessionDataTask *task;
46 -
47 -/**
48 - The unique identifier for the success and failure blocks when duplicate requests are made.
49 - */
50 -@property (nonatomic, strong) NSUUID *receiptID;
51 -@end
52 -
53 -/** The `AFImageDownloader` class is responsible for downloading images in parallel on a prioritized queue. Incoming downloads are added to the front or back of the queue depending on the download prioritization. Each downloaded image is cached in the underlying `NSURLCache` as well as the in-memory image cache. By default, any download request with a cached image equivalent in the image cache will automatically be served the cached image representation.
54 - */
55 -@interface AFImageDownloader : NSObject
56 -
57 -/**
58 - The image cache used to store all downloaded images in. `AFAutoPurgingImageCache` by default.
59 - */
60 -@property (nonatomic, strong, nullable) id <AFImageRequestCache> imageCache;
61 -
62 -/**
63 - The `AFHTTPSessionManager` used to download images. By default, this is configured with an `AFImageResponseSerializer`, and a shared `NSURLCache` for all image downloads.
64 - */
65 -@property (nonatomic, strong) AFHTTPSessionManager *sessionManager;
66 -
67 -/**
68 - Defines the order prioritization of incoming download requests being inserted into the queue. `AFImageDownloadPrioritizationFIFO` by default.
69 - */
70 -@property (nonatomic, assign) AFImageDownloadPrioritization downloadPrioritizaton;
71 -
72 -/**
73 - The shared default instance of `AFImageDownloader` initialized with default values.
74 - */
75 -+ (instancetype)defaultInstance;
76 -
77 -/**
78 - Creates a default `NSURLCache` with common usage parameter values.
79 -
80 - @returns The default `NSURLCache` instance.
81 - */
82 -+ (NSURLCache *)defaultURLCache;
83 -
84 -/**
85 - Default initializer
86 -
87 - @return An instance of `AFImageDownloader` initialized with default values.
88 - */
89 -- (instancetype)init;
90 -
91 -/**
92 - Initializes the `AFImageDownloader` instance with the given session manager, download prioritization, maximum active download count and image cache.
93 -
94 - @param sessionManager The session manager to use to download images.
95 - @param downloadPrioritization The download prioritization of the download queue.
96 - @param maximumActiveDownloads The maximum number of active downloads allowed at any given time. Recommend `4`.
97 - @param imageCache The image cache used to store all downloaded images in.
98 -
99 - @return The new `AFImageDownloader` instance.
100 - */
101 -- (instancetype)initWithSessionManager:(AFHTTPSessionManager *)sessionManager
102 - downloadPrioritization:(AFImageDownloadPrioritization)downloadPrioritization
103 - maximumActiveDownloads:(NSInteger)maximumActiveDownloads
104 - imageCache:(nullable id <AFImageRequestCache>)imageCache;
105 -
106 -/**
107 - Creates a data task using the `sessionManager` instance for the specified URL request.
108 -
109 - If the same data task is already in the queue or currently being downloaded, the success and failure blocks are
110 - appended to the already existing task. Once the task completes, all success or failure blocks attached to the
111 - task are executed in the order they were added.
112 -
113 - @param request The URL request.
114 - @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`.
115 - @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred.
116 -
117 - @return The image download receipt for the data task if available. `nil` if the image is stored in the cache.
118 - cache and the URL request cache policy allows the cache to be used.
119 - */
120 -- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request
121 - success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success
122 - failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure;
123 -
124 -/**
125 - Creates a data task using the `sessionManager` instance for the specified URL request.
126 -
127 - If the same data task is already in the queue or currently being downloaded, the success and failure blocks are
128 - appended to the already existing task. Once the task completes, all success or failure blocks attached to the
129 - task are executed in the order they were added.
130 -
131 - @param request The URL request.
132 - @param receiptID The identifier to use for the download receipt that will be created for this request. This must be a unique identifier that does not represent any other request.
133 - @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`.
134 - @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred.
135 -
136 - @return The image download receipt for the data task if available. `nil` if the image is stored in the cache.
137 - cache and the URL request cache policy allows the cache to be used.
138 - */
139 -- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request
140 - withReceiptID:(NSUUID *)receiptID
141 - success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success
142 - failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure;
143 -
144 -/**
145 - Cancels the data task in the receipt by removing the corresponding success and failure blocks and cancelling the data task if necessary.
146 -
147 - If the data task is pending in the queue, it will be cancelled if no other success and failure blocks are registered with the data task. If the data task is currently executing or is already completed, the success and failure blocks are removed and will not be called when the task finishes.
148 -
149 - @param imageDownloadReceipt The image download receipt to cancel.
150 - */
151 -- (void)cancelTaskForImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt;
152 -
153 -@end
154 -
155 -#endif
156 -
157 -NS_ASSUME_NONNULL_END
1 -// 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 "SwiftWarplyFramework/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 "SwiftWarplyFramework/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 "SwiftWarplyFramework/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 "SwiftWarplyFramework/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 "SwiftWarplyFramework/AFHTTPSessionManager.h"
29 -#import "SwiftWarplyFramework/AFURLResponseSerialization.h"
30 -#import "SwiftWarplyFramework/AFURLRequestSerialization.h"
31 -
32 -@interface WKWebView (_AFNetworking)
33 -@property (readwrite, nonatomic, strong, setter = af_setURLSessionTask:) NSURLSessionDataTask *af_URLSessionTask;
34 -@end
35 -
36 -@implementation WKWebView (_AFNetworking)
37 -
38 -- (NSURLSessionDataTask *)af_URLSessionTask {
39 - return (NSURLSessionDataTask *)objc_getAssociatedObject(self, @selector(af_URLSessionTask));
40 -}
41 -
42 -- (void)af_setURLSessionTask:(NSURLSessionDataTask *)af_URLSessionTask {
43 - objc_setAssociatedObject(self, @selector(af_URLSessionTask), af_URLSessionTask, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
44 -}
45 -
46 -@end
47 -
48 -#pragma mark -
49 -
50 -@implementation WKWebView (AFNetworking)
51 -
52 -- (AFHTTPSessionManager *)sessionManager {
53 - static AFHTTPSessionManager *_af_defaultHTTPSessionManager = nil;
54 - static dispatch_once_t onceToken;
55 - dispatch_once(&onceToken, ^{
56 - _af_defaultHTTPSessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
57 - _af_defaultHTTPSessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
58 - _af_defaultHTTPSessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
59 - });
60 -
61 - return objc_getAssociatedObject(self, @selector(sessionManager)) ?: _af_defaultHTTPSessionManager;
62 -}
63 -
64 -- (void)setSessionManager:(AFHTTPSessionManager *)sessionManager {
65 - objc_setAssociatedObject(self, @selector(sessionManager), sessionManager, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
66 -}
67 -
68 -- (AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer {
69 - static AFHTTPResponseSerializer <AFURLResponseSerialization> *_af_defaultResponseSerializer = nil;
70 - static dispatch_once_t onceToken;
71 - dispatch_once(&onceToken, ^{
72 - _af_defaultResponseSerializer = [AFHTTPResponseSerializer serializer];
73 - });
74 -
75 - return objc_getAssociatedObject(self, @selector(responseSerializer)) ?: _af_defaultResponseSerializer;
76 -}
77 -
78 -- (void)setResponseSerializer:(AFHTTPResponseSerializer<AFURLResponseSerialization> *)responseSerializer {
79 - objc_setAssociatedObject(self, @selector(responseSerializer), responseSerializer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
80 -}
81 -
82 -#pragma mark -
83 -
84 -- (void)loadRequest:(NSURLRequest *)request
85 - progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress
86 - success:(NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success
87 - failure:(void (^)(NSError *error))failure
88 -{
89 - [self loadRequest:request MIMEType:nil textEncodingName:nil progress:progress success:^NSData *(NSHTTPURLResponse *response, NSData *data) {
90 - NSStringEncoding stringEncoding = NSUTF8StringEncoding;
91 - if (response.textEncodingName) {
92 - CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)response.textEncodingName);
93 - if (encoding != kCFStringEncodingInvalidId) {
94 - stringEncoding = CFStringConvertEncodingToNSStringEncoding(encoding);
95 - }
96 - }
97 -
98 - NSString *string = [[NSString alloc] initWithData:data encoding:stringEncoding];
99 - if (success) {
100 - string = success(response, string);
101 - }
102 -
103 - return [string dataUsingEncoding:stringEncoding];
104 - } failure:failure];
105 -}
106 -
107 -- (void)loadRequest:(NSURLRequest *)request
108 - MIMEType:(NSString *)MIMEType
109 - textEncodingName:(NSString *)textEncodingName
110 - progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress
111 - success:(NSData * (^)(NSHTTPURLResponse *response, NSData *data))success
112 - failure:(void (^)(NSError *error))failure
113 -{
114 - NSParameterAssert(request);
115 -
116 - if (self.af_URLSessionTask.state == NSURLSessionTaskStateRunning || self.af_URLSessionTask.state == NSURLSessionTaskStateSuspended) {
117 - [self.af_URLSessionTask cancel];
118 - }
119 - self.af_URLSessionTask = nil;
120 -
121 - __weak __typeof(self)weakSelf = self;
122 - __block NSURLSessionDataTask *dataTask;
123 - dataTask = [self.sessionManager
124 - dataTaskWithRequest:request
125 - uploadProgress:nil
126 - downloadProgress:nil
127 - completionHandler:^(NSURLResponse * _Nonnull response, id _Nonnull responseObject, NSError * _Nullable error) {
128 - __strong __typeof(weakSelf) strongSelf = weakSelf;
129 - if (error) {
130 - if (failure) {
131 - failure(error);
132 - }
133 - } else {
134 - if (success) {
135 - success((NSHTTPURLResponse *)response, responseObject);
136 - }
137 - [strongSelf loadData:responseObject MIMEType:MIMEType characterEncodingName:textEncodingName baseURL:[dataTask.currentRequest URL]];
138 -
139 - if ([strongSelf.UIDelegate respondsToSelector:@selector(webViewDidFinishLoad:)]) {
140 - [strongSelf.UIDelegate webViewDidClose:strongSelf];
141 - }
142 - }
143 - }];
144 - self.af_URLSessionTask = dataTask;
145 - if (progress != nil) {
146 - *progress = [self.sessionManager downloadProgressForTask:dataTask];
147 - }
148 - [self.af_URLSessionTask resume];
149 -
150 - if ([self.UIDelegate respondsToSelector:@selector(webViewDidStartLoad:)]) {
151 - //[self.UIDelegate webViewDidStartLoad:self];
152 - }
153 -}
154 -
155 -@end
156 -
157 -#endif
1 -#import "FMDatabase.h"
2 -#import "FMResultSet.h"
3 -#import "FMDatabaseAdditions.h"
4 -#import "FMDatabaseQueue.h"
5 -#import "FMDatabasePool.h"
1 -//
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
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 could not be displayed because it is too large.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.