使用PHP从Swift连接到在线数据库(mySQL)。 (XCODE)

时间:2015-02-01 06:15:21

标签: ios mysql json xcode swift

我想将我的xcode应用程序连接到在线数据库并从中获取数据并在我的应用程序中显示+使用我的应用程序将数据写入在线数据库。我已经完成了应用程序,但现在它给了我一个错误。

错误: enter image description here

我的网页上有我的在线数据库,我已经将两个php文件上传到我的网络文件管理器中。一个php文件检索我的数据库中的所有数据并将它们编码为json。第二个php文件执行查询,从我的应用程序将数据写入我的在线数据库。

enter image description here

如上图所示,我成功获得json输出,但当我尝试将数据放入xcode中的数组时,它给了我这个错误。

这是我的代码

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet var tableview: UITableView!
    @IBOutlet var inputFriendName: UITextField!
    @IBOutlet var inputFriendInfo: UITextField!

    var data: NSArray = []

    override func viewDidLoad() {
        super.viewDidLoad()
        data = dataOfJson("http://bishanonline.com/extra/serviceselect.php")
        println(data)

    }

    @IBAction func reload() {
        data = dataOfJson("http://bishanonline.com/extra/serviceselect.php")
        self.tableview.reloadData()
    }

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        self.view.endEditing(true)
    }

    func dataOfJson(url: String) -> NSArray {
        var data = NSData(contentsOfURL: NSURL(string: url)!)
        return (NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: nil) as NSArray)
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell: additionInfoCell = self.tableview.dequeueReusableCellWithIdentifier("customCell") as additionInfoCell
        var maindata = (data[indexPath.row] as NSDictionary)
        cell.friendName!.text = maindata["Name"] as? String
        cell.friendInfo!.text = maindata["Additional Info"] as? String
        return cell
    }

    @IBAction func uploadToDatabase() {
        var url: NSString = "http://bishanonline.com/extra/servicequery.php?x=\(inputFriendName.text)&y=\(inputFriendInfo.text)"
        url = url.stringByReplacingOccurrencesOfString(" ", withString: "%20")
        url = url.stringByReplacingOccurrencesOfString("/n", withString: "%0A")
        var data = NSData(contentsOfURL: NSURL(string: url)!)
        var result = NSString(data: data!, encoding: NSUTF8StringEncoding)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

问题出现在此代码行中

 func dataOfJson(url: String) -> NSArray {
    var data = NSData(contentsOfURL: NSURL(string: url)!)
    return (NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: nil) as NSArray)
}

请帮我把json数据放到数组中。感谢任何帮助。

2 个答案:

答案 0 :(得分:4)

最后解决了问题。首先,我将详细说明确切的问题然后解决方案将被发布。 你正在做的代码完全没问题,但真正的问题是你的后端

  

对于serviceselect.php

您为获取记录所做的代码是

func dataOfJson(url: String) -> NSArray 
{
   var data = NSData(contentsOfURL: NSURL(string: url)!)
   return (NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: nil) as NSArray)
}
This above method is returing NSArray but the data you are getting from the server is kinda messed up because along with JSON data some garbage data is included as well.Check out the below image

enter image description here

因此,当尝试从上面的字符串生成JSON数据时,我们会遇到崩溃和错误。     可能是由于免费托管服务,我们收到此消息(不确定)

  

解决方案

   func getallrecords(){
    let url = NSURL(string: "http://bishanonline.com/extra/serviceselect.php")
    let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
        var d = NSString(data: data, encoding: NSUTF8StringEncoding)
        var arr = d!.componentsSeparatedByString("<") // spliting the incoming string from "<" operator because before that operator is our required data and storing in array
        var dataweneed:NSString = arr[0] as NSString // arr[0] is the data before "<" operator and arr[1] is actually no use for us
         if let data = NSJSONSerialization.JSONObjectWithData(dataweneed.dataUsingEncoding(NSUTF8StringEncoding)!, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSArray

// JSONObjectWithData始终具有 NSData 的第一个参数,但我们的 dataweneed 实际上是NSString,所以我们实际上是将NSString转换为NSData

   {
            for dd in data{
                var name : String = dd["Name"]! as String
                var info : String = dd["Additional Info"]! as String
                println("Name is : \(name)") // MainDeveloper for 0 and BestBuddy for 1 index
                println("Info is : \(info)") // Bishan for 0 and AkilaPrabath for 1 index
     }
        }
    }

    task.resume()
    }

最终输出

Finall output

  

对于servicequery.php

   func addrecord(x:String,y:String){
   let request = NSMutableURLRequest(URL: NSURL(string: "http://bishanonline.com/extra/servicequery.php")!)
            var postString : String = "x="+x+"&y="+y
            request.HTTPMethod = "GET"
            request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
            let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
                data, response, error in

                if error != nil {
                    println("error=\(error)")
                    return
                }


                let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary

                if jsonResult as String == "Successfully added "
                {
                 // Show an alert to notify user
                }
           }
            task.resume()
           }

同时删除“echo $ query;”在servicequery.php的第30行

答案 1 :(得分:1)

尝试使用此代码解析服务器中的JSON

//created NSURL
let requestURL = NSURL(string: URL_GET_TEAMS)


//creating NSMutableURLRequest
let request = NSMutableURLRequest(URL: requestURL!)

//setting the method to post
request.HTTPMethod = "GET"

//creating a task to send the post request
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
    data, response, error in

    //exiting if there is some error
    if error != nil{
        print("error is \(error)")
        return;
    }

    //parsing the response
    do {
        //converting resonse to NSArray
        let myJSON =  try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSArray


        //looping through all the json objects in the array teams
        for i in 0 ..< myJSON.count{

            myJSON[i]["object key here"]
        }

    } catch {
        print(error)
    }
}
//executing the task
task.resume()

来源: json parsing in ios swift