NSURL(string:fullURL)返回错误

时间:2016-06-26 10:59:33

标签: ios swift nsurl

您好我将一些数据传递给webservice。这是我的网址

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}]

这是我的网络服务调用methid

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放在浏览器中时它会给我服务响应。这是什么原因?请帮我。 感谢

3 个答案:

答案 0 :(得分:1)

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

urlString.stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet())

答案 1 :(得分:1)

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

  

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

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

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

答案 2 :(得分:0)

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

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

现在在url初始化中传递此NSURL

希望这会对你有所帮助。