In SwiftUI
, we are developing an application that retrieves and uses data through API
connections.
When retrieving data from an application under development in SwiftUI by GET method on an API connection, the data cannot be retrieved if the search criteria parameter is a string containing &
or =
.
For example,
http://sample.com/api/book/
If you have a base endpoint with a string of URLs as your search criteria, such as ?url=
:
:: You can get the value by setting the parameters as follows.
http://sample.com/api/book/?url=`https://nicebook.com/detail/id/106639`
:: You can't get it if:
http://sample.com/api/book/?url=`https://nicebook.com/detail/?id=106639&category=history`
In the case of の, the symbol ?
, =
is included in the string set as a parameter, and I don't think it's going to be the expected movement. What are the countermeasures in this case?
When connecting to the API, the code is as follows:
func fetchApiData(){
let url_1 = "https://nicebook.com/detail/id/106639"
let url_2="https://nicebook.com/detail/?id=106639&category=history"
var endpoint="http://sample.com/api/book/?url="+url_1// OK
// var endpoint="http://sample.com/api/book/?url="+url_2NG
varencodeEndpoint=endpoint.addingPercentEncoding(withAllowedCharacters:.urlQueryAllowed)??"
// Setup the URL request
guard let url = URL (string:encodeEndpoint) else {
print("Error: cannot create URL")
return
}
let urlRequest = URLRequest (url:URL)
// setup the session
let config = URLSessionConfiguration.default
let session = URLSession(configuration:config)
// make the request
let task = session.dataTask(with:urlRequest) {
(data, response, error) in
// check for any errors
guard error == nil else {
print("error calling GET")
return
}
// make sure we got data
guardlet responseData=data else{
print("Error: did not receive data")
return
}
// parse the result as JSON, since that's what the API offers
DispatchQueue.main.async {
do {self.bookInfos=try JSONDecoder().decode([BookInfo].self, from:responseData)
Print(self.bookInfos as Any)//url_2 does not get a value (console->[])
}catch {
print("Error: did not decode")
return
}
}
}
task.resume()
}
Using the article here, I tried to encode the parameter URL separately, but it didn't work.
let url_2="https://nicebook.com/detail/?id=106639&category=history"
url_2.addEndpoint.addPercentEncoding (withAllowedCharacters:.urlPathAllowed)!
var endpoint="http://sample.com/api/book/?url="+url_2
varencodeEndpoint=endpoint.addingPercentEncoding(withAllowedCharacters:.urlQueryAllowed)??"
Swift 5.0
swift api
I was able to make ends meet by editing it as follows.
var urlComps=URLComponents (string:endpoint)!
urlComps.queryItems=[URLQueryItem(name: "url", value:url_2)]
guard let url = urlComps.urlelse {
print("Error: cannot create URL")
return
}
© 2024 OneMinuteCode. All rights reserved.