如果服务器没有应答则超时

Timeout if server does not answer

我的 VC 中有这样的代码:

    if Reachability.isConnectedToNetwork() == true {
        print("Internet connection OK")

         JSONParseFunc()

    } else {
        print("Internet connection FAILED")
        let alert = UIAlertView(title: "you're not conneted to internet ", message: "make sure you're connected to server ", delegate: nil, cancelButtonTitle: "OK")
        alert.show()
    }

其中我检查了互联网的可达性,但我想检查服务器是否正在发送数据,我需要为此设置超时,我如何在这段代码中实现超时是我的JSON函数:

func JSONParseFunc(){



        let requestURL: NSURL = NSURL(string: "XXXXXXX")!
        let urlRequest: NSMutableURLRequest = NSMutableURLRequest(url: requestURL as URL)
        let session = URLSession.shared
        let task = session.dataTask(with: urlRequest as URLRequest) {
            (data, response, error) -> Void in


            let readableJSON = JSON(data: data! , options: JSONSerialization.ReadingOptions.mutableContainers, error: nil)

            self.nrows = readableJSON.count

            for i in 0...self.nrows{

                if let Name = readableJSON[i]["Name"].string as String! {
                    var ID = readableJSON[i]["Id"].intValue
                    var iDString = String (ID)

                    var desc = readableJSON[i]["Description"].string as String!


                    self.iDArray.append(iDString)

                    self.description1.append(desc!)
                    self.namesArray.append(Name)


                }




            }

            self.tableView.reloadData()
        }
        task.resume()

    self.tableView.reloadData()


    }

试试这样设置这个

 var session = URLSession()
 override init() {
        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 30.0
        configuration.timeoutIntervalForResource = 60.0
        session = URLSession(configuration: configuration)

    }