Bishan Bishan - 3 months ago 31
Swift Question

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

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.

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.

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.

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.

Answer

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

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)

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 NSData but our dataweneed is actually NSString so we are actually converting NSString to 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

For 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

Comments