Skip to content

Instantly share code, notes, and snippets.

@digoreis
Created May 15, 2018 22:21
Show Gist options
  • Save digoreis/6d4de6f4c583bb07745ef38890fdcfe7 to your computer and use it in GitHub Desktop.
Save digoreis/6d4de6f4c583bb07745ef38890fdcfe7 to your computer and use it in GitHub Desktop.
Fórum do Swift
//: Playground - noun: a place where people can play
import Foundation
import PlaygroundSupport
struct Post {
let id: Int
let body: String
let username: String
let name: String
init(dict: Dictionary<String,AnyObject>) {
self.body = dict["cooked"] as! String
self.name = dict["name"] as! String
self.username = dict["username"] as! String
self.id = dict["id"] as! Int
}
}
var isFinalPage = false
let url = "https://forums.swift.org/t/se-0207-add-a-containsonly-algorithm-to-sequence/11686[PAGE].json"
var postcount = 0
var dataRequest: URLSessionDataTask?
var posts = [Post]()
var titleForum: String?
func generateURL() -> String {
print("url generate")
if posts.count > 0 {
return url.replacingOccurrences(of: "[PAGE]", with: "/\(posts.count)")
}
return url.replacingOccurrences(of: "[PAGE]", with: "")
}
func loadPage() {
print("load page")
guard !isFinalPage else { return }
guard let url = URL(string: generateURL()) else { print("NO URL") ; return }
dataRequest = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
guard let dataJSON = data else { print("NO DATA") ; isFinalPage = true ; return }
guard let jsonDict = try? JSONSerialization.jsonObject(with: dataJSON, options: []) as? [String: AnyObject] else { print("NO JSON"); isFinalPage = true ; return }
guard let json = jsonDict else { isFinalPage = true ; return }
guard let postsDict = json["post_stream"]?["posts"] as? [Dictionary<String,AnyObject>] else { isFinalPage = true ; return }
postcount = json["posts_count"] as? Int ?? 0
titleForum = json["title"] as? String ?? ""
posts.append(contentsOf: postsDict.map({ Post(dict: $0) }))
finishLoadind()
})
dataRequest?.resume()
}
func finishLoadind() {
if posts.count < postcount {
loadPage()
} else {
isFinalPage = true
print(titleForum ?? "")
print(posts)
}
}
PlaygroundPage.current.needsIndefiniteExecution = true
print("start")
loadPage()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment