Search code examples
iosswifttimeoutreachability

Timeout if server does not answer


I have code in my VC like this :

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

in which I check the reachability of internet, but I want to check if the server is sending data or not, I need to set timeout for this purpose, how do I achieve time out in this code here is my JSON function:

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


    }

Solution

  • Try to set this one like that

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