Dilip Tiwari
Dilip Tiwari

Reputation: 1451

response Data is nil

I am getting response data nil.

func fetchSinglePageData() {
    var response: NSData?
    var errors: NSError?
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {

        response = NSData(contentsOfFile:"url...?project_id=(self.projectID)&project_page=Request", options: NSDataReadingOptions(0), error: &errors)

        print("LatestURL Single page:(response)")

        if response == nil {
            var alertview = UIAlertView(title: "Network Error", message: "Data not received due to network connection.Try again...", delegate: self, cancelButtonTitle: "Ok")
            alertview.show()
        }
        else{
            let jsonDict: NSDictionary = NSJSONSerialization.JSONObjectWithData(response!, options: nil, error: &errors) as NSDictionary
            print("JSON Response Single page:(jsonDict)")
            var statuses = [NSObject : AnyObject]()
            self.lblstartTime?.text = jsonDict["start_time"] as? String
            self.lblcurrentStage?.text = jsonDict["current_stage"] as? String
            self.lblcompletionTime?.text = jsonDict["completion_time"] as? String
            self.lblManager?.text = jsonDict["manager"] as? String
        }
    })
}    

project_id is string which is recevied from presvious page which is correctly working.

Upvotes: 2

Views: 2687

Answers (4)

Dilip Tiwari
Dilip Tiwari

Reputation: 1451

func singlePageData(){

    var errors: NSError?

    let urlString = "xyz.com"
    print("URL RESPONSE  \(urlString)")

    let request = NSURLRequest(URL: NSURL(string: urlString), cachePolicy: .ReloadIgnoringLocalCacheData, timeoutInterval: 50)

    let session = NSURLSession.sharedSession()

    let task = session.dataTaskWithRequest(request) { (data, response, error) in

        if error != nil{
            //handel error
            print(error!.localizedDescription)
            var alertview = UIAlertView(title: "Network Error", message: "Data not received due to network connection.Try again...", delegate: self, cancelButtonTitle: "Ok")
            alertview.show()
            return
        }

        if let responseData = data{

              var jsonDict: NSDictionary = NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.MutableContainers, error: &errors) as NSDictionary!

            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {

            println("Json dict value  \(jsonDict)")
            self.lblprojectName?.text = jsonDict["name"] as? String
            println("lblprojectName:  \(self.lblprojectName?.text)")
            self.lblstartTime?.text = jsonDict["start_time"] as? String
             println("lblstartTime :  \(self.lblstartTime?.text)")
            self.lblcurrentStage?.text = jsonDict["current_stage"] as? String
             println("lblcurrentStage :  \(self.lblcurrentStage?.text)")
            self.lblcompletionTime?.text = jsonDict["completion_time"] as? String
             println("lblcompletionTime :  \(self.lblcompletionTime?.text)")
            self.lblManager?.text = jsonDict["manager"] as? String

            })

            }
        }
    task.resume()

}

This is my answer as per Jitendra Solanki answer i have made changes to code and it is now working in Swift 1.2

Upvotes: 1

Jitendra Solanki
Jitendra Solanki

Reputation: 772

In swift 3

 //make a url request

 let urlString = "your_url"
 let urlRequest = URLRequest.init(url: URL.init(string: urlString)!, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 50)

  //create a session
  let session = URLSession.shared

  let task = session.dataTask(with: request) { (data, urlResponse, error) in
        if error != nil{
            //handle error
            return
        }else{
            if let responseData = data{
             let  jsonDict  = try JSONSerialization.jsonObject(with: responseData, options: [])as? [String:Any]
             //handle your response here

            }
        }
    }
  task.resume()

In swift 2.2

    let urlString = "your_url"

    let request = NSURLRequest(URL: NSURL(string: urlString)!, cachePolicy: .ReloadIgnoringLocalCacheData, timeoutInterval: 50)

    let session = NSURLSession.sharedSession()

    let task = session.dataTaskWithRequest(request) { (data, response, error) in

        if error != nil{
            //handel error
            print(error!.localizedDescription)
            return
        }

        if let responseData = data{

            do{
                if  let jsonDict = try NSJSONSerialization.JSONObjectWithData(responseData, options: [])as? [String:Any]{

                    //you have data in json dict

                }

            }catch{
                print("error in parsing response")
                return
            }


        }
    }
    task.resume()

Upvotes: 1

Scriptable
Scriptable

Reputation: 19750

In this line:

response   = NSData(contentsOfFile:"url...?project_id=(self.projectID)&project_page=Request", options: NSDataReadingOptions(0), error: &errors)

you have project_id=(self.projectID), to use interpolation you should instead have project_id=\(self.projectID)

I would suggest that you separate the code to generate your full URL, then print the URL to the console and ensure that it is what you would expect.

Then you can visit the url yourself and check to see what the server returns, then once you know you have the correct URL and response you can then work to deserialise the response

EDIT: updated with URLSession (Swift 3 version)

let defaultSession = URLSession(configuration: URLSessionConfiguration.default)
var dataTask: URLSessionDataTask?
let projectID = 12
let url = URL(string: "http://phpyouth.com/clients/halfpricedgrannyflats/app/app_response.php?project_id=\(projectID)&project_page=Request")

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

    if let error = error {
        print(error.localizedDescription)
    } else if let httpResponse = response as? HTTPURLResponse {
        if httpResponse.statusCode == 200 {
            if let responseData = data {
                if let json = try? JSONSerialization.jsonObject(with: responseData, options: .allowFragments) as? [String:AnyObject] {
                    print(json)
                }
            }
        }
    }
}

dataTask?.resume()

Upvotes: 0

user6338195
user6338195

Reputation:

After a quick look, maybe \ missing:

NSData(contentsOfFile:"url...?project_id=\(self.projectID)&project_page=Request"

Upvotes: 0

Related Questions