iOS Swift NSURL Web 地址不起作用 [英] iOS Swift NSURL Web Address Not Working

查看:58
本文介绍了iOS Swift NSURL Web 地址不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从服务器获取数据.我的网址是(例如):http://dommain.com/action

当我执行

让 nsURL = NSURL(fileURLWithPath: url)

URL 被翻译成 http://domain.com/action.然后当我执行这个:

let task = NSURLSession.sharedSession().dataTaskWithURL(nsURL) {(数据,响应,错误)在打印(数据=\(数据)响应=\(响应)错误=\(错误)")}

错误属性说它找不到file:///http://domain.com/action

我不确定我做错了什么.

解决方案

替换

让 nsURL = NSURL(fileURLWithPath: url)

let nsURL = NSURL(string: url)

<块引用>

NSURL 对象表示一个 URL,它可能包含远程服务器上资源的位置、磁盘上本地文件的路径,甚至是任意一段编码数据.

NSURL(fileURLWithPath: url) 初始化并返回一个新创建的 NSURL 对象作为具有指定路径的 file URL.对于网络 URL,请改用 NSURL(string: url).

<小时>

对于 Swift 3 及更高版本,使用 URL 而不是 NSURL:

let u = URL(string: url)

I'm attempting to get data from a server. My URL is (for example): http://dommain.com/action

When I execute

let nsURL = NSURL(fileURLWithPath: url)

the URL gets translated into http:/domain.com/action. Then when I execute this:

let task = NSURLSession.sharedSession().dataTaskWithURL(nsURL) {
    (data, response, error) in
    print("data=\(data) response=\(response) error=\(error)")
}

the error property says it can't find "file:///http:/domain.com/action

I'm not sure what I'm doing wrong.

解决方案

Replace

let nsURL = NSURL(fileURLWithPath: url)

with

let nsURL = NSURL(string: url)

An NSURL object represents a URL that can potentially contain the location of a resource on a remote server, the path of a local file on disk, or even an arbitrary piece of encoded data.

NSURL(fileURLWithPath: url) initializes and returns a newly created NSURL object as a file URL with a specified path. For network URL use NSURL(string: url) instead.


For Swift 3 and upwards, use URL instead of NSURL:

let u = URL(string: url)

这篇关于iOS Swift NSURL Web 地址不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆