简体   繁体   中英

View JSON feed Swift 3.0

I am trying to view my php result in an IOS app. The code is the following:

 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]


    }

The code is working fine for the w3schools link, however it crashes when I use my link (hosted on go daddy) If you open the links from a web browser, we get the intended result.

This is the error received:

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

Any help would be much appreciated

As Eric Aya mentioned in his comment. The issue is that your PHP service spits out the JSON data into an HTML page.

When I view source of your page I get the following:

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

The page source of the w3schools url is simply JSON. In your PHP service, output your data in JSON and you should be good to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM