Skip to content

Commit ee85321

Browse files
authored
Merge pull request #161 from pusher/set-subscriptions
Implement setSubscriptions
2 parents ff1ee6a + b038d42 commit ee85321

File tree

8 files changed

+112
-58
lines changed

8 files changed

+112
-58
lines changed

CHANGELOG.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,14 @@
11
# Changelog
2+
All notable changes to this project will be documented in this file.
3+
4+
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
5+
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
6+
7+
## [Unreleased](https://github.com/pusher/pusher-websocket-swift/compare/5.1.0...HEAD)
8+
9+
## [5.1.0](https://github.com/pusher/pusher-websocket-swift/compare/5.0.1...5.1.0) - 2017-11-23
10+
## Added
11+
- [`setSubscriptions`](https://pusher.com/docs/push_notifications/reference/client_api#put-v1clientsclientidinterests) method.
212

313
## 5.0.1
414

PusherSwift.podspec

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
Pod::Spec.new do |s|
22
s.name = 'PusherSwift'
3-
s.version = '5.0.1'
3+
s.version = '5.1.0'
44
s.summary = 'A Pusher client library in Swift'
55
s.homepage = 'https://github.com/pusher/pusher-websocket-swift'
66
s.license = 'MIT'

Sources/Info.plist

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
<key>CFBundlePackageType</key>
1616
<string>FMWK</string>
1717
<key>CFBundleShortVersionString</key>
18-
<string>5.0.1</string>
18+
<string>5.1.0</string>
1919
<key>CFBundleSignature</key>
2020
<string>????</string>
2121
<key>CFBundleVersion</key>

Sources/NativePusher.swift

Lines changed: 96 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,22 @@ import Foundation
156156
addSubscriptionChangeToTaskQueue(interestName: interestName, change: .subscribe)
157157
}
158158

159+
/**
160+
Subscribe to interests with Pusher's Push Notification Service
161+
162+
- parameter interests: the name of the interests you want to subscribe to
163+
*/
164+
open func setSubscriptions(interests: Array<String>) {
165+
requestQueue.tasks += { _, next in
166+
self.replaceSubscriptionSet(
167+
interests: interests,
168+
successCallback: next
169+
)
170+
}
171+
172+
requestQueue.run()
173+
}
174+
159175
/**
160176
Unsubscribe from an interest with Pusher's Push Notification Service
161177

@@ -176,7 +192,7 @@ import Foundation
176192
*/
177193
private func addSubscriptionChangeToTaskQueue(interestName: String, change: SubscriptionChange) {
178194
requestQueue.tasks += { _, next in
179-
self.modifySubscription(
195+
self.subscribeOrUnsubscribeInterest(
180196
interest: interestName,
181197
change: change,
182198
successCallback: next
@@ -188,98 +204,125 @@ import Foundation
188204

189205
/**
190206
Makes either a POST or DELETE request for a given interest
191-
192-
- parameter pusherAppKey: The app key for the Pusher app
193-
- parameter clientId: The clientId returned by Pusher's server
194-
- parameter interest: The name of the interest to be subscribed to /
195-
unsunscribed from
207+
- parameter interest: The name of the interest to be subscribed to / unsunscribed from
196208
- parameter change: Whether to subscribe or unsubscribe
197209
- parameter callback: Callback to be called upon success
198210
*/
199-
private func modifySubscription(interest: String, change: SubscriptionChange, successCallback: @escaping (Any?) -> Void) {
200-
guard pusherAppKey != nil && clientId != nil else {
201-
self.delegate?.debugLog?(message: "pusherAppKey \(String(describing: pusherAppKey)) or clientId \(String(describing: clientId)) not set - waiting for both to be set")
211+
private func subscribeOrUnsubscribeInterest(interest: String, change: SubscriptionChange, successCallback: @escaping (Any?) -> Void) {
212+
guard
213+
let clientId = clientId,
214+
let pusherAppKey = pusherAppKey
215+
else {
216+
self.delegate?.debugLog?(message: "pusherAppKey or clientId not set - waiting for both to be set")
202217
self.requestQueue.pauseAndResetCurrentTask()
203218
return
204219
}
205220

206-
self.delegate?.debugLog?(message: "Attempt number: \(self.failedRequestAttempts + 1) of \(maxFailedRequestAttempts)")
221+
let url = "\(CLIENT_API_V1_ENDPOINT)/clients/\(clientId)/interests/\(interest)"
222+
let params: [String: Any] = ["app_key": pusherAppKey]
223+
let request = self.setRequest(url: url, params: params, change: change)
224+
self.doURLRequest(interests: [interest], request: request, change: change, successCallback: successCallback)
225+
}
207226

208-
let url = "\(CLIENT_API_V1_ENDPOINT)/clients/\(clientId!)/interests/\(interest)"
209-
var request = URLRequest(url: URL(string: url)!)
210-
request.httpMethod = change.httpMethod()
227+
/**
228+
Makes a PUT request for given interests
229+
- parameter interests: The name of the interests to be subscribed to
230+
- parameter callback: Callback to be called upon success
231+
*/
232+
private func replaceSubscriptionSet(interests: Array<String>, successCallback: @escaping (Any?) -> Void) {
233+
guard
234+
let clientId = clientId,
235+
let pusherAppKey = pusherAppKey
236+
else {
237+
self.delegate?.debugLog?(message: "pusherAppKey or clientId not set - waiting for both to be set")
238+
self.requestQueue.pauseAndResetCurrentTask()
239+
return
240+
}
211241

212-
let params: [String: Any] = ["app_key": pusherAppKey!]
213-
try! request.httpBody = JSONSerialization.data(withJSONObject: params, options: [])
242+
let url = "\(CLIENT_API_V1_ENDPOINT)/clients/\(clientId)/interests/"
243+
let params: [String: Any] = ["app_key": pusherAppKey, "interests": interests]
244+
let request = self.setRequest(url: url, params: params, change: .setSubscriptions)
245+
self.doURLRequest(interests: interests, request: request, change: .setSubscriptions, successCallback: successCallback)
246+
}
214247

215-
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
216-
request.addValue(LIBRARY_NAME_AND_VERSION, forHTTPHeaderField: "X-Pusher-Library")
248+
private func doURLRequest(interests: Array<String>, request: URLRequest, change: SubscriptionChange, successCallback: @escaping (Any?) -> Void) {
249+
self.delegate?.debugLog?(message: "Attempt number: \(self.failedRequestAttempts + 1) of \(maxFailedRequestAttempts)")
217250

218251
let task = URLSession.dataTask(
219252
with: request,
220253
completionHandler: { data, response, error in
221254
guard let httpResponse = response as? HTTPURLResponse,
222-
(200 <= httpResponse.statusCode && httpResponse.statusCode < 300) &&
223-
error == nil
224-
else {
225-
self.failedRequestAttempts += 1
226-
227-
if error != nil {
228-
self.delegate?.debugLog?(message: "Error when trying to modify subscription to interest: \(String(describing: error?.localizedDescription))")
229-
} else if data != nil && response != nil {
230-
let responseBody = String(data: data!, encoding: .utf8)
231-
self.delegate?.debugLog?(message: "Bad response from server: \(response!) with body: \(String(describing: responseBody))")
232-
} else {
233-
self.delegate?.debugLog?(message: "Bad response from server when trying to modify subscription to interest: \(interest)")
234-
}
235-
236-
if self.failedRequestAttempts >= self.maxFailedRequestAttempts {
237-
self.delegate?.debugLog?(message: "Max number of failed native service requests reached")
238-
239-
self.requestQueue.paused = true
240-
} else {
241-
self.delegate?.debugLog?(message: "Retrying subscription modification request for interest: \(interest)")
242-
self.requestQueue.retry(Double(self.failedRequestAttempts * self.failedRequestAttempts))
243-
}
244-
245-
return
255+
(200 <= httpResponse.statusCode && httpResponse.statusCode < 300) &&
256+
error == nil
257+
else {
258+
self.failedRequestAttempts += 1
259+
260+
if error != nil {
261+
self.delegate?.debugLog?(message: "Error when trying to modify subscription to interest(s): \(String(describing: error?.localizedDescription))")
262+
} else if data != nil && response != nil {
263+
let responseBody = String(data: data!, encoding: .utf8)
264+
self.delegate?.debugLog?(message: "Bad response from server: \(response!) with body: \(String(describing: responseBody))")
265+
} else {
266+
self.delegate?.debugLog?(message: "Bad response from server when trying to modify subscription to interest(s): \(interests)")
267+
}
268+
269+
if self.failedRequestAttempts >= self.maxFailedRequestAttempts {
270+
self.delegate?.debugLog?(message: "Max number of failed native service requests reached")
271+
272+
self.requestQueue.paused = true
273+
} else {
274+
self.delegate?.debugLog?(message: "Retrying subscription modification request for interest(s): \(interests)")
275+
self.requestQueue.retry(Double(self.failedRequestAttempts * self.failedRequestAttempts))
276+
}
277+
278+
return
246279
}
247280

248281
switch change {
249282
case .subscribe:
283+
guard let interest = interests.first else { return }
250284
self.delegate?.subscribedToInterest?(name: interest)
285+
case .setSubscriptions:
286+
self.delegate?.subscribedToInterests?(interests: interests)
251287
case .unsubscribe:
288+
guard let interest = interests.first else { return }
252289
self.delegate?.unsubscribedFromInterest?(name: interest)
253290
}
254291

255-
self.delegate?.debugLog?(message: "Success making \(change.stringValue) to \(interest)")
292+
self.delegate?.debugLog?(message: "Success making \(change.rawValue) to \(interests)")
256293

257294
self.failedRequestAttempts = 0
258295
successCallback(nil)
259-
}
296+
}
260297
)
261298

262299
task.resume()
263300
}
301+
302+
private func setRequest(url: String, params: [String: Any], change: SubscriptionChange) -> URLRequest {
303+
var request = URLRequest(url: URL(string: url)!)
304+
request.httpMethod = change.httpMethod()
305+
306+
try! request.httpBody = JSONSerialization.data(withJSONObject: params, options: [])
307+
308+
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
309+
request.addValue(LIBRARY_NAME_AND_VERSION, forHTTPHeaderField: "X-Pusher-Library")
310+
311+
return request
312+
}
264313
}
265314

266-
internal enum SubscriptionChange {
315+
internal enum SubscriptionChange: String {
267316
case subscribe
317+
case setSubscriptions
268318
case unsubscribe
269319

270-
internal func stringValue() -> String {
271-
switch self {
272-
case .subscribe:
273-
return "subscribe"
274-
case .unsubscribe:
275-
return "unsubscribe"
276-
}
277-
}
278-
279320
internal func httpMethod() -> String {
280321
switch self {
281322
case .subscribe:
282323
return "POST"
324+
case .setSubscriptions:
325+
return "PUT"
283326
case .unsubscribe:
284327
return "DELETE"
285328
}

Sources/PusherDelegate.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
@objc optional func registeredForPushNotifications(clientId: String)
1313
@objc optional func failedToRegisterForPushNotifications(response: URLResponse, responseBody: String?)
1414
@objc optional func subscribedToInterest(name: String)
15+
@objc optional func subscribedToInterests(interests: Array<String>)
1516
@objc optional func unsubscribedFromInterest(name: String)
1617

1718
@objc optional func changedConnectionState(from old: ConnectionState, to new: ConnectionState)

Sources/PusherSwift.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
import Foundation
99

1010
let PROTOCOL = 7
11-
let VERSION = "5.0.1"
11+
let VERSION = "5.1.0"
1212
let CLIENT_NAME = "pusher-websocket-swift"
1313

1414
@objcMembers

Tests/Info.plist

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
<key>CFBundlePackageType</key>
1616
<string>BNDL</string>
1717
<key>CFBundleShortVersionString</key>
18-
<string>5.0.1</string>
18+
<string>5.1.0</string>
1919
<key>CFBundleSignature</key>
2020
<string>????</string>
2121
<key>CFBundleVersion</key>

Tests/PusherClientInitializationTests.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import PusherSwift
1010
import XCTest
1111

12-
let VERSION = "5.0.1"
12+
let VERSION = "5.1.0"
1313

1414
class ClientInitializationTests: XCTestCase {
1515
var key: String!

0 commit comments

Comments
 (0)