-1

I have pdf url, I want to know the code how to store that pdf in my phone memory. I want to store that pdf and want to view that pdf from phone. I am using swift 4 and Xcode for coding

sachit
  • 21
  • 2

1 Answers1

1

Swift 4

Call this function only pass url and after downloading it will be return file url........

func get_file(httpUrl:String)
    {
        let documentsUrl =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let url = URL(string: httpUrl)!
        let destinationUrl = documentsUrl.appendingPathComponent(url.lastPathComponent)

        let session = URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: nil)
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        let task = session.dataTask(with: request, completionHandler:
        {
            data, response, error in
            if error == nil
            {
                if let response = response as? HTTPURLResponse
                {
                    if response.statusCode == 200
                    {
                        if let data = data
                        {
                            if let _ = try? data.write(to: destinationUrl, options: Data.WritingOptions.atomic)
                            {
                                print(destinationUrl.absoluteString)
                            }
                            else
                            {
                                print(error!)
                            }
                        }
                        else
                        {
                            print(error!)
                        }
                    }
                }
            }
            else
            {
                print(error!)
            }
        })
        task.resume()

    }

here you caught your file ..

let documentsUrl =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let url = URL(string: file_str)!
        let destinationUrl = documentsUrl.appendingPathComponent(url.lastPathComponent)
Divyesh Gondaliya
  • 884
  • 11
  • 21