我尝试使用orderId作为参数发出GET请求以从API端点检索图像数据。当我在URL字符串中硬编码orderId时,请求成功。但是,当我在函数中将orderId作为参数传递时,我收到错误。如何解决此问题?
public func getImage(orderId : String, completionHandler: @escaping (String?)-> ()) {
parameters = [:]
do {
let postData = try JSONSerialization.data(withJSONObject: parameters, options: [])
}catch{
print(error.localizedDescription)
completionHandler(nil)
}
let request = NSMutableURLRequest(url: NSURL(string: "https://api.neural.love/v1/ai-art/orders/\(orderId)")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if let _ = error {
print("error description: \(error.debugDescription)")
}
guard let data = data else{
completionHandler(nil)
return
}
let str = String(decoding: data, as: UTF8.self)
print("string of data \(str)")
if let dict = self.convertToDictionary(text: str), let outputArr = dict["output"] as? [[String:Any]], let firstOutput = outputArr.first, let imgUrl = firstOutput["full"] as? String {
completionHandler(imgUrl)
}
completionHandler(nil)
})
dataTask.resume()
}
1条答案
按热度按时间brvekthn1#
由于
orderId
是动态的,从API响应中获取,它可能包含特殊字符,这可能会在创建URL时导致问题。因此,我们需要addingPercentEncoding
作为路径组件,因为orderId
位于URL路径中。