React Native Swift 转义闭包
React Native Swift Escaping closure
我正在尝试使用 Swift 为 IOS 在 React native 中实现本机模块。
我有一个函数 getRandomFoodWithCompletionHandler()
我试图从 API 获取一些东西,然后使用 promises 通过桥将它发送回 JS。
我使用 resolve:RCTPromiseResolveBlock 函数,但是当我使用它时出现错误
转义闭包捕获非转义参数'resolve'
struct Food: Identifiable, Decodable {
var id: Int
var uid: String
var dish: String
var description: String
var ingredient: String
var measurement: String
}
@objc
func getRandomFoodWithCompletionHandler(_ resolve:RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
guard let url = URL(string: "https://random-data-api.com/api/food/random_food") else { fatalError("Missing URL") }
let urlRequest = URLRequest(url: url)
let dataTask = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
if let error = error {
print("Request error: ", error)
return
}
guard (response as? HTTPURLResponse)?.statusCode == 200 else { return }
guard let data = data else { return }
do {
let decodedFood = try JSONDecoder().decode(Food.self, from: data)
print("Completion handler decodedFood", decodedFood)
resolve(decodedFood)
} catch {
print("Error decoding", error)
}
}
dataTask.resume()
}
使您的 resolve: RCTPromiseResolveBlock
参数成为转义块:
func getRandomFoodWithCompletionHandler(
_ resolve: @escaping RCTPromiseResolveBlock,
reject: @escaping RCTPromiseRejectBlock
) {
“转义”块本质上是一个即使在原始函数已经完成执行时也可以调用的块,例如当它是异步完成处理程序时。
在Swift中因为内存的关系需要区分这种情况allocations/deallocations.
我正在尝试使用 Swift 为 IOS 在 React native 中实现本机模块。
我有一个函数 getRandomFoodWithCompletionHandler() 我试图从 API 获取一些东西,然后使用 promises 通过桥将它发送回 JS。 我使用 resolve:RCTPromiseResolveBlock 函数,但是当我使用它时出现错误 转义闭包捕获非转义参数'resolve'
struct Food: Identifiable, Decodable {
var id: Int
var uid: String
var dish: String
var description: String
var ingredient: String
var measurement: String
}
@objc
func getRandomFoodWithCompletionHandler(_ resolve:RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
guard let url = URL(string: "https://random-data-api.com/api/food/random_food") else { fatalError("Missing URL") }
let urlRequest = URLRequest(url: url)
let dataTask = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
if let error = error {
print("Request error: ", error)
return
}
guard (response as? HTTPURLResponse)?.statusCode == 200 else { return }
guard let data = data else { return }
do {
let decodedFood = try JSONDecoder().decode(Food.self, from: data)
print("Completion handler decodedFood", decodedFood)
resolve(decodedFood)
} catch {
print("Error decoding", error)
}
}
dataTask.resume()
}
使您的 resolve: RCTPromiseResolveBlock
参数成为转义块:
func getRandomFoodWithCompletionHandler(
_ resolve: @escaping RCTPromiseResolveBlock,
reject: @escaping RCTPromiseRejectBlock
) {
“转义”块本质上是一个即使在原始函数已经完成执行时也可以调用的块,例如当它是异步完成处理程序时。 在Swift中因为内存的关系需要区分这种情况allocations/deallocations.