我的数据库连接迅速无法正常工作

时间:2018-12-04 20:54:49

标签: swift database

我正在尝试从Localhost数据库中获取数据。我在Mac上运行MAMP,并已构建Web服务器。我已经制作了一个php脚本,当我用浏览器访问它时,它会返回数据。我的Swift代码中出现了问题,该代码应从URL会话中获取数据并进行解析。在downloadItems()函数下方,数据和错误变量返回nil值,但是响应变量返回表明连接正在工作的数据。我希望data变量具有我的php正在从数据库中删除的数据。

import Foundation

protocol FeedModelProtocol: class {
    func itemsDownloaded(items: NSArray)
}

class FeedModel: NSObject, URLSessionDataDelegate {       
    weak var delegate: FeedModelProtocol!        
    let urlPath = "http://x*//MyWebService/api/Get_Data2.php" //Change to the web address of your stock_service.php file

    func downloadItems() {            
        let url: URL = URL(string: urlPath)!
        let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default)

        let task = defaultSession.dataTask(with: url) { (data, response, error) in

            if error != nil {
                print("Error")
            }else {
                print("stocks downloaded")
                print(error!)
                print(data!)
                print(response!)
                self.parseJSON(data!)
            }               
        }

        task.resume()
    }

    func parseJSON(_ data:Data) {            
        var jsonResult = NSArray()

        do{
            jsonResult = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSArray

        } catch let error as NSError {
            print(error)                
        }

        var jsonElement = NSDictionary()
        let stocks = NSMutableArray()

        for i in 0 ..< jsonResult.count {                
            jsonElement = jsonResult[i] as! NSDictionary                
            let stock = StockModel()

            //the following insures none of the JsonElement values are nil through optional binding
            if let name = jsonElement["name"] as? String,
                let price = jsonElement["price"] as? String {
                print(name)
                print(price)
                stock.name = name
                stock.price = price
            }                
            stocks.add(stock)                
        }

        DispatchQueue.main.async(execute: { () -> Void in                
            self.delegate.itemsDownloaded(items: stocks)                
        })
    }
}

0 个答案:

没有答案