Skip to content

Instantly share code, notes, and snippets.

@eduardo22i
Created December 15, 2017 15:54
Show Gist options
  • Save eduardo22i/0ee8960c36659b17fbc538964e929cac to your computer and use it in GitHub Desktop.
Save eduardo22i/0ee8960c36659b17fbc538964e929cac to your computer and use it in GitHub Desktop.
An Extension of Firebase Messaging To Get Topics
extension Messaging {
static private let accessToken = "" //Server Web Key
struct Topic : Decodable {
var name : String?
var addDate : String?
}
struct Rel : Decodable {
var topics = [Topic]()
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let relContainer = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .rel)
let topicsContainer = try relContainer.nestedContainer(keyedBy: CodingKeys.self, forKey: .topics )
for key in topicsContainer.allKeys {
var topic = Topic()
topic.name = key.stringValue
let topicContainer = try? topicsContainer.nestedContainer(keyedBy: CodingKeys.self, forKey: key)
topic.addDate = try! topicContainer?.decode(String.self, forKey: .addDate)
self.topics.append(topic)
}
}
struct CodingKeys : CodingKey {
var stringValue: String
init?(stringValue: String) {
self.stringValue = stringValue
}
var intValue: Int? { return nil }
init?(intValue: Int) { return nil }
static let rel = CodingKeys(stringValue: "rel")!
static let topics = CodingKeys(stringValue: "topics")!
static let addDate = CodingKeys(stringValue: "addDate")!
}
}
func loadTopics(block : @escaping (_ topics: [Messaging.Topic]?, _ error: Error?) -> Void ) {
if let token = InstanceID.instanceID().token() {
let url = URL(string: "https://iid.googleapis.com/iid/info/\(token)?details=true")!
var request = URLRequest(url: url)
request.addValue("key=\(Messaging.accessToken)", forHTTPHeaderField: "Authorization")
let dataTask = URLSession.shared.dataTask(with: request) { (data, response, error) in
DataManager.shared.make(request: urlRequest, block: { (data, error) in
if let data = data {
let decoder = JSONDecoder()
let rel = try? decoder.decode(Rel.self, from: data)
block(rel?.topics, error)
} else {
block(nil, error)
}
}
dataTask.resume()
}
}
}
// Usage
Messaging.messaging().loadTopics { (topics, error) in
topics?.forEach({ (topic) in
print(topic.name)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment