3

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.

9
  • your site is not opening in the browser.Kindly resolve then comment i will give you the code after testing on your site's link Commented Feb 1, 2015 at 12:53
  • @Johnny here is the proper link bishanonline.com/extra/serviceselect.php bishanonline.com/extra/servicequery.php Sorry for the link i've updated it on code too. Appreciate any help. Commented Feb 1, 2015 at 13:24
  • This is the response i am getting inside xcode.As you can see there is some extra script file in there please remove that so that only json response is printed. Optional([{"Name":"Bishan","Additional Info":"MainDeveloper"},{"Name":"AkilaPrabath","Additional Info":"BestBuddy"}] <!-- Hosting24 Analytics Code --> <script type="text/javascript" src="stats.hosting24.com/count.php"></script> <!-- End Of Analytics Code --> ) Commented Feb 1, 2015 at 14:02
  • remove this <!-- Hosting24 Analytics Code --> <script type="text/javascript" src="stats.hosting24.com/count.php"></script>; <!-- End Of Analytics Code --> Commented Feb 1, 2015 at 14:03
  • @Johnny there is no such code lines in my php knw! Commented Feb 1, 2015 at 14:14

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank u soo much @johnny its working!! but actually as in my code i want to return NSArray from getallrecords function. Can u suggest me a way to do it? im not good with this :) i'm sending url from viewDidLoad to getallrecords() method. Here is the code : override func viewDidLoad() { super.viewDidLoad() data = getallrecords("bishanonline.com/extra/serviceselect.php") println(data) } And getallrecords must return NSArray cus i want to get the results into var data: NSArray = [] Can u suggest me a proper way to do that?
my "let data" is also an array then i just looping thorough it.You have to do the same.Simple return data variable from this function and loop on it
1

Try this code to parse JSON from server

//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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.