响应数据为零

Posted

技术标签:

【中文标题】响应数据为零【英文标题】:response Data is nil 【发布时间】:2017-05-01 11:52:02 【问题描述】:

我正在获取响应数据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 是从正常工作的上一页接收的字符串。

【问题讨论】:

使用 URLSession 从服务器获取数据。 raywenderlich.com/110458/nsurlsession-tutorial-getting-started 【参考方案1】:

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

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

【讨论】:

@DilipTiwari,我编辑了答案以在 swift 2.2 中工作,所有版本的方法都相同,只是 swift3 中更改了 api 方法的名称。我认为在 swift 1.2 中工作不应该有太多的变化,你可以使用 swift 2.2 的代码。 让我们continue this discussion in chat。【参考方案2】:
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()


这是我根据 Jitendra Solanki 的回答我已经对代码进行了更改,它现在可以在 Swift 1.2 中使用

【讨论】:

【参考方案3】:

快速浏览后,可能\丢失了:

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

【讨论】:

【参考方案4】:

在这一行:

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

你有project_id=(self.projectID),要使用插值,你应该有project_id=\(self.projectID)

我建议您将代码分开以生成完整的 URL,然后将 URL 打印到控制台并确保它是您所期望的。

然后您可以自己访问该 url 并检查服务器返回的内容,然后一旦您知道您有正确的 URL 和响应,您就可以对响应进行反序列化

编辑:更新为 URLSession(Swift 3 版本)

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

【讨论】:

该 url 包含 self.projectID 而不是实际的项目 ID。您需要使用\(self.projectID) 将值传入字符串 那么带有 projectID 的新 URL 是什么?你有错误吗?你最好使用 NSURLSession 我可以看到您使用的是旧版本的 xcode 和 swift。我已经提供了一个示例,说明您如何做到这一点,但它在 Swift 3 中。我使用 xcode 8。如果您打算将此应用程序推送到商店,您将需要更新,我相信苹果现在已经停止支持 ios9 及以下版本 您为什么删除了已接受的答案?这没有帮助吗?

以上是关于响应数据为零的主要内容,如果未能解决你的问题,请参考以下文章

AFNetworking 无法序列化压缩响应(响应对象为零)

响应式设计:为啥高度为零和 padding-bottom 可以使 div 响应大小?

completionHandler 的响应为零

解码后JSON数据为零

运行 ROS 服务时,IMU 客户端响应值全为零

集合视图第一个单元大小问题