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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28260055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 06:34:58  来源:igfitidea点击:

Connect to an online database (mySQL) from Swift, using PHP. (XCODE)

iosmysqljsonxcodeswift

提问by Bishan

I want to connect my xcode app to online database and get the data from it and display in my app + write the data into online database using my app. I've already done with app but now it gives me an error.

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

ERROR : enter image description here

错误 : 在此处输入图片说明

I have my online database in my web page and i have uploaded two php files into the file manager in my web. One php file retrieving all the data in my database and encoding them to json. And second php file doing the query to write data into my online database from my app.

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

enter image description here

在此处输入图片说明

As in above pic im getting json output successfully but when i try to get the data into an array in xcode it gives me that error.

就像上面的图片一样,我成功地获得了 json 输出,但是当我尝试将数据放入 xcode 中的数组时,它给了我那个错误。

This is my code

这是我的代码

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.
    }
}

Issue is in this code lines

问题出在此代码行中

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

Please help me to get json data into array. Appreciate any help.

请帮助我将 json 数据放入数组。感谢任何帮助。

回答by Talha Qamar

Finally problem resolved.First i am going to elaborate the exact problem then the solution will be posted. The code you were doing was totally fine but the real problem was your backend

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

For serviceselect.php

对于 serviceselect.php

The code you have done for fetching records is

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

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

在此处输入图片说明

So when try to generate JSON data from above string we are getting crashes and errors. May be due to free hosting service we are getting this message (Not sure)

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

Solution

解决方案

   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 always have first argument of NSDatabut our dataweneedis actually NSString so we are actually converting NSString to NSData

// 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()
    }

Final output

最终输出

Finall output

Finall output

For servicequery.php

对于 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()
           }

Also remove "echo $query;" on line 30 of servicequery.php

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

回答by Reyaan Roy

Try this code to parse JSON from server

尝试使用此代码从服务器解析 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()

Source: json parsing in ios swift

来源:ios swift中json解析