首页 > 解决方案 > Siri Shortcut Intent API 调用说 URL 是 nil,但它不是

问题描述

这是我正在处理的代码:

let url = "https://www.host.com/url/\(intent.cardInfo!)"
print(url)
    
let url2 = URL(string: url)! // this is nil??
    
let request = NSMutableURLRequest(url: url2)

下图显示此值不为零(您可以在控制台中看到)。我在 Siri 意图之后得到了价值。这是 IntentHandler 的内部。所有的代码都在下面。

class SoldForAppIntentHandler : NSObject, SoldForAppIntentHandling {

    func handle(intent: SoldForAppIntent, completion: @escaping (SoldForAppIntentResponse) -> Void) {
        print(intent.sport!)
        print(intent.cardInfo!)
        print(intent.cardNumber!)

        
        let url = "https://www.host.com/url/\(intent.cardInfo!)"
        print(url)
        
        let url2 = URL(string: url)!
        
        let request = NSMutableURLRequest(url: url2)
        request.httpMethod = "GET"

        let postString = ""
        request.httpBody = postString.data(using: String.Encoding.utf8)
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

        let task = URLSession.shared.dataTask(with: request as URLRequest) {
            data, response, error in

            if error != nil {
                print("error=\(error)")
                return
            }


            let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)

            do {
                let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
                //print(json!)
                let response = json!["value"] as! String

            } catch {
                print(" error adding tap search to db:\(error)")

            }

            print()

        }
        task.resume()
        
        
        
        completion(SoldForAppIntentResponse.success(response: "\n\nSold For will look up \(intent.sport!) \(intent.cardInfo!) \(intent.cardNumber!)"))
        
        
        
    }

在此处输入图像描述

标签: iosswift

解决方案


问题实际上是url2本身,因为字符串https://www.host.com/url/1986 fleer 57 Michael Jordan PSA 10无法正确转换为URL对象。

你可以尝试这样的事情:

if let url = "https://www.host.com/url/\(intent.cardInfo!)".addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) {
    let url2 = URL(string: url)!
}

推荐阅读