【问题标题】:NSURL(string: fullURL) returns errorNSURL(string: fullURL) 返回错误
【发布时间】:2016-06-26 10:59:33
【问题描述】:

您好,我正在将一些数据传递给 Web 服务。这是我的网址

http://www.website.com/mobileapp/user.php?reg_device_id=566&alert_details=[{\n    \"is_active\" = 1;\n    \"term_id\" = 55;\n}, {\n    \"is_active\" = 1;\n    \"term_id\" = 2;\n}, {\n    \"is_active\" = 1;\n    \"term_id\" = 111;\n}, {\n    \"is_active\" = 0;\n    \"term_id\" = 21;\n}, {\n    \"is_active\" = 0;\n    \"term_id\" = 28;\n}, {\n    \"is_active\" = 0;\n    \"term_id\" = 1;\n}, {\n    \"is_active\" = 0;\n    \"term_id\" = 5;\n}, {\n    \"is_active\" = 0;\n    \"term_id\" = 4;\n}]

这是我的网络服务调用方法

for i in 0..<dm.array.count {
        let id=dm.SettingsItems[i]["term_id"] as! String
        var is_active="0"

        if dm.array[i]
        {
            is_active="1"
        }

        let catRegDict:NSDictionary=["term_id":"\(id)","is_active":"\(is_active)"]
        self.registerAyrray.append(catRegDict)
        print("------REGISTER ARRAY------\(self.registerAyrray)")
    }
    let urlPath = "http://www.website.com/mobileapp/user.php?"
    let path="reg_device_id=\(dm.DeviceID)&alert_details=\(self.registerAyrray)"

    let fullURL = "\(urlPath)\(path)"
    print(fullURL)


    guard let endpoint = NSURL(string: fullURL) else {
        print("Error creating endpoint")
        return
    }

    let request = NSMutableURLRequest(URL:endpoint)
    NSURLSession.sharedSession().dataTaskWithRequest(request,completionHandler:  { (data, response, error) in
        do {

但似乎这个条件并不令人满意。我可以看到它显示此错误消息。

guard let endpoint = NSURL(string: fullURL) else {
    print("Error creating endpoint")
    return
}

但是当我将上面的 url 放入浏览器时,它给了我服务响应。这是什么原因?请帮我。 谢谢

【问题讨论】:

    标签: ios swift nsurl


    【解决方案1】:

    这是因为您的网址不是有效的网址。使用前必须encode url

    urlString.stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet())
    

    【讨论】:

      【解决方案2】:

      网址不能包含空格、“[”或各种其他字符。如果您阅读有关 URLWithString 的 Xcode 文档,他们会说:

      用来初始化 NSURL 对象的 URL 字符串。必须是一个 符合 RFC 2396 的 URL。此方法根据 URLString 解析 RFC 1738 和 1808。

      在线查找这些 RFC 以获取更多信息。

      @Arsen 为您提供了正确转义 URL 的代码,但您为什么要尝试发送包含空格的 URL,以及如何生成 alert_details 的查询字符串? alert_details 字符串看起来有点像印刷精美的 JSON。您不应该为 URL 参数使用漂亮的打印格式。

      【讨论】:

      • 它是一个像这样的数组 var registerAyrray:Array = Array () 如何将其转换为纯文本?
      【解决方案3】:

      尝试对您进行编码url,然后像这样创建NSURL 对象。

      let url = fullURL.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
      

      现在在NSURL 初始化中传递这个url

      希望这会对你有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-10-26
        • 1970-01-01
        • 2016-11-24
        • 1970-01-01
        • 1970-01-01
        • 2018-10-03
        • 1970-01-01
        • 2011-11-07
        相关资源
        最近更新 更多