簡體   English   中英

Swift 並發 UIButton

[英]Swift Concurrency UIButton

是否可以在 UIKit 中使用 async/await 來處理 POST HTTP 請求,即來自UIButton的請求?

我可以發送請求,但它會立即崩潰。 使用URLSession完美工作,以此作為學習經驗。

lazy var buttonTest: UIButton = {
    let button = UIButton()
    button.addTarget(self, action: #selector(testAsyncTwo), for: .touchUpInside)
    return button
}()

@objc func testAsync() async throws {
    let date = Date()
    let df = DateFormatter()
    df.dateFormat = "yyyy-MM-dd HH:mm:ss"
    let dateString = df.string(from: date)

    let json: [String: Any] = ["item": "1",
                               "time": "\(dateString)"]
    let jsonData = try? JSONSerialization.data(withJSONObject: json)
    
    guard let url = URL(string: "https://myapiendpoint.com/api/") else { fatalError("Missing URL") }
    var urlRequest = URLRequest(url: url)
    let token: String = "mySecretKey"
    urlRequest.setValue("Token \(token)", forHTTPHeaderField: "Authorization")
    urlRequest.httpMethod = "POST"
    urlRequest.setValue("\(String(describing: jsonData?.count))", forHTTPHeaderField: "Content-Length")
    urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
    urlRequest.httpBody = jsonData
    let (data, response) = try await URLSession.shared.data(for: urlRequest)
    
    guard (response as? HTTPURLResponse)?.statusCode == 200 else { fatalError("Error while fetching data") }
    let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
    if let responseJSON = responseJSON as? [String: Any] {
        print(responseJSON) //Code after Successfull POST Request
    }
}

非常感謝!

崩潰與您的URLSession代碼無關。 問題是您已將按鈕的選擇器聲明為異步拋出函數。 這與@objc選擇器不兼容。

代替:

@objc func testAsync() async throws { 
    ... 
}

和:

@objc func didTapButton(_ sender: Any) {
    Task {
        try await testAsync()
    }
}

func testAsync() async throws {
    ...
}

關鍵的觀察是@objc方法不是一個異步函數。 我還會給按鈕處理程序一個sender參數和一個更具描述性的名稱,以遵循既定的約定並一目了然地表明它正在處理按鈕點擊。

顯然,當您這樣做時,您也必須更改#selector引用:

button.addTarget(self, action: #selector(didTapButton(_:)), for: .touchUpInside)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM