swift 使用NSURL时出现错误当我在URL字符串中硬编码orderId时,请求成功,如何解决此问题?

hts6caw3  于 2023-02-03  发布在  Swift
关注(0)|答案(1)|浏览(98)

我尝试使用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()
    }
brvekthn

brvekthn1#

由于orderId是动态的,从API响应中获取,它可能包含特殊字符,这可能会在创建URL时导致问题。因此,我们需要addingPercentEncoding作为路径组件,因为orderId位于URL路径中。

let original = "https://api.neural.love/v1/ai-art/orders/\(orderId)"
if let encoded = original.addingPercentEncoding(withAllowedCharacters: . urlPathAllowed),
let url = URL(string: encoded)
{
    print(url)
}

相关问题