查看JSON feed Swift 3.0

时间:2016-11-30 14:48:03

标签: php ios json swift

我试图在IOS应用程序中查看我的php结果。 代码如下:

 func get()
    {
        //let url = NSURL(string: "http://www.w3schools.com/js/customers_mysql.php")
        let url = NSURL(string: "http://www.helpmewastetime.com/service.php")
        let data = NSData(contentsOf: url! as URL)

        values = try! JSONSerialization.jsonObject(with: data! as Data, options: JSONSerialization.ReadingOptions.allowFragments) as! NSArray


        var array = [""]
        array = (values.value(forKey: "Name") as? [String])!
        lb_Value.text = array[0]


    }

代码在w3schools链接上工作正常,但是当我使用我的链接时它会崩溃(托管在爸爸身上) 如果您从Web浏览器打开链接,我们会得到预期的结果。

这是收到的错误:

2016-11-30 16:44:24.977781 Fun iOS App[2590:112849] [] __nw_connection_get_connected_socket_block_invoke 2 Connection has no connected handler
2016-11-30 16:44:24.979616 Fun iOS App[2590:112846] PAC stream failed with
2016-11-30 16:44:24.981519 Fun iOS App[2590:112849] [] nw_proxy_resolver_create_parsed_array PAC evaluation error: kCFErrorDomainCFNetwork: 2
2016-11-30 16:44:26.145018 Fun iOS App[2590:112849] [] nw_endpoint_handler_add_write_request [1.1.1 107.180.54.250:80 failed socket-flow (satisfied)] cannot accept write requests
2016-11-30 16:44:26.145764 Fun iOS App[2590:112847] [] __tcp_connection_write_eof_block_invoke Write close callback received error: [22] Invalid argument
2016-11-30 16:44:26.150620 Fun iOS App[2590:112846] [] nw_proxy_resolver_create_parsed_array PAC evaluation error: kCFErrorDomainCFNetwork: 2
fatal error: 'try!' expression unexpectedly raised an error: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}: file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-800.0.58.6/src/swift/stdlib/public/core/ErrorType.swift, line 178

非常感谢任何帮助

1 个答案:

答案 0 :(得分:3)

Eric Aya在评论中提到。问题是您的PHP服务将JSON数据吐出到HTML页面中。

当我查看您的页面来源时,我得到以下内容:

<html>
[{"ID":"1","Name":"Peter"},{"ID":"2","Name":"James"}]
</html>

w3schools网址的页面来源只是JSON。在你的PHP服务中,用JSON输出你的数据,你应该很高兴。