response Data is nil

浪尽此生 提交于 2019-12-11 06:57:20

问题


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.


回答1:


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



回答2:


func singlePageData(){

    var errors: NSError?

    let urlString = "http://phpyouth.com/clients/halfpricedgrannyflats/app/app_response.php?project_id=\(self.projectID)&project_page=Request"
    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




回答3:


After a quick look, maybe \ missing:

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



回答4:


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


来源:https://stackoverflow.com/questions/43718675/response-data-is-nil

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!