Eti*_*ule 0 grand-central-dispatch alamofire swift3 xcode8.1
好的,我对这一个感到疯狂......
我正在使用Alamofire 4.x(Swift 3和XCode 8.1).我需要从需要身份验证的站点获取和解析几个html请求(不幸的是没有json API).然后用Fuzi解析HTML,这个进展可能需要一些时间,所以我打算使用ProgressHUD(准确地说PKHUD)让用户知道发生了什么.我还需要获取一些不在身份验证后面的html.
我创建了一个结构和函数来处理整个网络进程并解析数据.
我设法执行请求并获取我需要的数据,但我似乎无法弄清楚如何在正确的时间进行HUD更新.
到目前为止,这是我的代码:
import Alamofire
import Fuzi
import PKHUD
struct MyMSCProvider {
static let baseUrl = "http://mastersswimming.ca"
//I tried with or without a custom queue - same result
static let processingQueue = DispatchQueue(label: "com.colddiver.processing-queue", qos: .utility)
static func fetchData(data: MscRequest) {
if data.profile || data.log {
//Authenticate first!
HUD.show(.labeledProgress(title: "Authenticating", subtitle: ""))
let requestUrl = "\(baseUrl)/MyMscPage.jsp"
let parameters = ["locale": "en", "username": data.user.username, "password": data.user.password]
Alamofire.request(requestUrl, method: .post, parameters: parameters).responseData(
queue: processingQueue,
completionHandler:
{ response in
// Now on the processingQueue you created earlier.
print("THREAD: \(Thread.current) is main thread: \(Thread.isMainThread)")
switch response.result {
case .success:
if data.profile {
DispatchQueue.main.async {
HUD.show(.labeledProgress(title: "Getting Profile", subtitle: ""))
}
let userProfile = parseProfile(data: response.data!, user: data.user)
print(userProfile)
}
if data.log {
DispatchQueue.main.async {
HUD.show(.labeledProgress(title: "Getting Log", subtitle: ""))
}
fetchLog()
}
if data.records {
DispatchQueue.main.async {
HUD.show(.labeledProgress(title: "Getting Records", subtitle: ""))
}
fetchRecords(recordsToFetch: data.recordsToFetch)
}
if data.times {
DispatchQueue.main.async {
HUD.show(.labeledProgress(title: "Getting Times", subtitle: ""))
}
print("Fetching times is not implemented yet")
}
DispatchQueue.main.async {
HUD.flash(.success)
}
case .failure(let error):
HUD.flash(.error)
print("Alamofire request failed")
print(error)
}
}
)
} else {
//Just fetch - no need to authenticate first
if data.records {
DispatchQueue.main.async {
HUD.show(.labeledProgress(title: "Getting Records", subtitle: ""))
}
fetchRecords(recordsToFetch: data.recordsToFetch)
}
if data.times {
print("Fetching times is not implemented yet")
}
DispatchQueue.main.async {
HUD.flash(.success)
}
}
}
static func fetchRecords(recordsToFetch: RecordsToFetch) {
for province in recordsToFetch.provinces {
for ageGroup in recordsToFetch.ageGroups {
for gender in recordsToFetch.genders {
DispatchQueue.main.async {
HUD.show(.labeledProgress(title: "Getting Records", subtitle: "\(province) - \(gender+Helpers.getAgeGroupFromAge(age: Int(ageGroup)!))"))
}
let requestUrl = "\(baseUrl)/Records.jsp"
let parameters = ["locale": "en", "province": province, "age": ageGroup, "gender": gender, "course": "*"]
Alamofire.request(requestUrl, method: .post, parameters: parameters).responseData(
queue: processingQueue,
completionHandler: { response in
switch response.result {
case .success:
let recordArray = parseRecords(data: response.data!, province: province, ageGroup: ageGroup, gender: gender)
case .failure(let error):
DispatchQueue.main.async {
HUD.flash(.failure)
}
print("Alamofire request failed")
print(error)
}
}
)
}
}
}
}
static func fetchLog() {
let requestUrl = "\(baseUrl)/ViewLog.jsp"
Alamofire.request(requestUrl).responseData(
queue: processingQueue,
completionHandler: { response in
switch response.result {
case .success:
let log = parseLog(data: response.data!)
case .failure(let error):
DispatchQueue.main.async {
HUD.flash(.failure)
}
print("Alamofire request failed")
}
}
)
}
// MARK: - Convenience structs
struct MscRequest {
let profile: Bool
let log: Bool
let times: Bool
let records: Bool
let recordsToFetch: RecordsToFetch
let user: MscUser
let parentView: UITableViewController
}
Run Code Online (Sandbox Code Playgroud)
在这个设置下,我会在TableViewController中设置一个MscRequest并启动一系列请求,如下所示:
let myData = MscRequest.init(
profile: true,
log: true,
times: false,
records: true,
recordsToFetch: RecordsToFetch.init(
provinces: ["NB", "CA"],
ageGroups: ["20", "25", "30", "35", "40"],
genders: ["M", "F"]),
user: MscUser.init(
username: "SomeUserName",
password: "SomePassword"),
parentView: self
)
MyMSCProvider.fetchData(data: myData)
Run Code Online (Sandbox Code Playgroud)
通过此设置,所有HUD更新都在同一时间(在主线程上)完成,并且在后台获取和解析仍在进行时最终被解除.不完全是我想要的......
我尝试了各种迭代(有或没有自定义队列),我也直接从Alamofire的手册(省略了completionHandler部分)尝试了HTML请求代码,但我仍然得到相同的结果......
我还看了一下Grand Central Dispatch教程(比如这一篇:http://www.appcoda.com/grand-central-dispatch/),但我还没想出如何在使用Alamofire时应用信息......
值得注意的是,我设法使用手动NSURLRequests在Objective-C中完成这项工作.我正在将这个旧应用程序现代化到Swift 3,并认为我应该尝试Alamofire.
不禁觉得我错过了一些明显的东西......有什么提示吗?
好吧,我找到了一种方法来使用DispatchGroup(Swift 3,Alamofire 4.x)做我想做的事情
func fetchData() {
let requestGroup = DispatchGroup()
//Need as many of these statements as you have Alamofire.requests
requestGroup.enter()
requestGroup.enter()
requestGroup.enter()
Alamofire.request("http://httpbin.org/get").responseData { response in
print("DEBUG: FIRST Request")
requestGroup.leave()
}
Alamofire.request("http://httpbin.org/get").responseData { response in
print("DEBUG: SECOND Request")
requestGroup.leave()
}
Alamofire.request("http://httpbin.org/get").responseData { response in
print("DEBUG: THIRD Request")
requestGroup.leave()
}
//This only gets executed once all the above are done
requestGroup.notify(queue: DispatchQueue.main, execute: {
// Hide HUD, refresh data, etc.
print("DEBUG: all Done")
})
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1587 次 |
| 最近记录: |