0

I need to download a file, which is located on the server. I have an URL for it like: http://www.myhosting.com/1.txt I need to download it to my iOS device or, at least, read text from it. My project is on SWIFT. Now I am using a code below:

let requestURL: NSURL = NSURL(string: "http://www.myhosting.com/1.txt")!
        let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithRequest(urlRequest) {
            (data, response, error) -> Void in

            let httpResponse = response as! NSHTTPURLResponse
            let statusCode = httpResponse.statusCode

            if (statusCode == 200) {
                self.dtlbl.text = "Everyone is fine, file downloaded successfully."

            }
        }

        task.resume()

But it doesn't work. My app just closing up after running this code. I tried to read it, but it was unluck too..

Please, need any help! Dont know what to do. One more think - I SHOULDN'T use any side frameworks.

1 Answers1

0

The problem is to unwrap response without checking if it is nil or not.

let requestURL: NSURL = NSURL(string: "http://www.myhosting.com/1.txt")!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(urlRequest) {
  (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
  if let httpResponse = response as? NSHTTPURLResponse {
    let statusCode = httpResponse.statusCode
    if (statusCode == 200) {
      self.dtlbl.text = "Everyone is fine, file downloaded successfully."
    }
  }
}
task.resume()
Kenan Karakecili
  • 731
  • 6
  • 23