用swift从php页面拉json数组

时间:2017-02-11 22:11:11

标签: php swift xcode nsurlsessiondatatask

我有一个返回JSON数组的php页面,这里是php:

$sql ="SELECT * FROM SongTable";
if ($result = mysqli_query($con, $sql)) {
while ($row = mysqli_fetch_row($result)) {
   $allarray[] = $row;
}

echo json_encode($allarray, JSON_UNESCAPED_SLASHES);

在我的swift代码中,我想使用datataskwithURL下载JSON数组,然后将该数据保存到新数组中以便稍后使用。这是我的快捷代码。

import UIKit

class ViewController: UIViewController {


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    //Data Pull Section
    let url_to_request = (string: "********")
    let url:NSURL = NSURL(string: url_to_request)!
    let session = URLSession.shared
    let request = NSMutableURLRequest(url: url as URL)

    //request data from URL
    let task = session.dataTask(with: request as URLRequest) {
        (
        data, response, error) in

        guard let _:NSData = data as NSData?, let _:URLResponse = response, error == nil else {
            print("error")
            return
        }
        //create data string
        let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
        print(dataString! as NSString)

    }
} //close viewDidLoad

当我在Xcode中运行模拟器时,我没有收到任何错误,但我不知道如何确保其正常工作。我还需要将这些数据从url保存到xcode中的新数组。谢谢你的帮助!

0 个答案:

没有答案