I'm new to swift and am wondering how I can pass arguments into a function when that function has a completion. I tried just passing in a variable String but that did not work. Here is my class for handling an api request. This is where i need to pass the contents to so that it can add it to a search field and return the results.
public class API {
func apiRequest(search: String, completion: @escaping (Result) -> ()) {
//URL
var query = search.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
let url = URL(string: "https://calorieninjas.p.rapidapi.com/v1/nutrition?query=" + query!)
//URL REQUEST
var request = URLRequest(url: url!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)
//Specify header
let headers = [
"x-rapidapi-key": "3be44a36b7msh4d4738910c1ca4dp1c2825jsn96bcc44c2b19",
"x-rapidapi-host": "calorieninjas.p.rapidapi.com"
]
request.httpMethod="GET"
request.allHTTPHeaderFields = headers
//Get the URLSession
let session = URLSession.shared
//Create data task
let dataTask = session.dataTask(with: request) { (data, response, error) in
let result = try? JSONDecoder().decode(Result.self, from: data!)
print(result)
DispatchQueue.main.async {
completion(result!)
}
}
//Fire off data task
dataTask.resume()
}
}
This is my content view code where I am trying to pass in the contents of a text box into this function so that i can get the result back from the api:
struct ContentView: View {
@State var result = Result()
@State private var searchItem: String = ""
var body: some View {
ZStack(alignment: .top) {
Rectangle()
.fill(Color.myPurple)
.ignoresSafeArea(.all)
VStack {
TextField("Enter food", text: $searchItem)
.background(Color.white)
.padding()
.textFieldStyle(RoundedBorderTextFieldStyle())
SearchButton()
.padding(.top)
.onTapGesture {
API().apiRequest { (result) in //IDEALLY I WOULD LIKE TO PASS IN THE CONTENTS OF THE TEXT BOX HERE INTO apiRequest
self.result = result
}
}
}
}
}
}
I'm sure the solution is simple I am just not used to the syntax and such of swift quite yet any help with this is much appreciated.
Your function 'apiRequest' has 2 parameters:
So when you call this method, you will pass these 2 parameters as well, like this:
.onTapGesture {
API().apiRequest(search: "String you want to pass", completion: { (result) in
self.result = result
})
}
Learn about closures, as this completion parameter is also a type of closure (escaping closure).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.