I'm unable to download file sometimes its sometimes it is download or some give me error. Here is my code Please help:
let urlGetStr = urlStr + "?&requestSource=Mobile&requestData="+inputData;
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)
var request = try! URLRequest(url: URL(string: baseUrl + urlGetStr)!);
request.httpMethod = "GET";
//Create URL to the source file you want to download
//let session = URLSession.shared
session.downloadTask(with: request) { (tempLocalUrl, response, error) in
DispatchQueue.main.async
{
indicator.stopAnimating();
if let tempLocalUrl = tempLocalUrl, error == nil {
// Success
if let statusCode = (response as? HTTPURLResponse)?.statusCode {
print("Successfully downloaded. Status code: \(statusCode)")
}
do {
try FileManager.default.copyItem(at: tempLocalUrl, to: localFileStr)
self.doAfterFileDownload(localFileStr, viewController: viewController);
} catch (let writeError) {
print("Error creating a file \(localFileStr) : \(writeError)")
bondEvalueCommonView.showAlertDialog("Alert", message : "Unable to downlaod the document. Please try again after sometime or contact the support team.", btnText : "OK");
}
} else {
print("Error took place while downloading a file. Error description: %#", error?.localizedDescription as Any);
}
}
}.resume()
}
Related
I want to display html file from a folder in document directory. I downloaded a zip file than unzip it now I want to display html file in UIWebView.
I downloaded file from this URL: http://MyURL/D_Word_Meaning_Quiz/data_zip.zip
Download file this way :-
static func loadFileAsync(url: URL, completion: #escaping (String?, Error?) -> Void) {
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let destinationUrl = documentsUrl.appendingPathComponent(url.lastPathComponent)
if FileManager().fileExists(atPath: destinationUrl.path) {
completion(destinationUrl.path, nil)
} else {
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)
{
completion(destinationUrl.path, error)
}
else
{
completion(destinationUrl.path, error)
}
}
else
{
completion(destinationUrl.path, error)
}
}
}
}
else
{
completion(destinationUrl.path, error)
}
})
task.resume()
}
}
Unzip file this way:-
func unzipFolder(filePath: String){
do {
let convertedURL = URL.init(fileURLWithPath: filePath)
print(convertedURL)
let unzipDirectory = try Zip.quickUnzipFile(convertedURL)
print(unzipDirectory)
let htmlUrl = unzipDirectory.appendingPathComponent("index.html")
let req = URLRequest(url: htmlUrl)
DispatchQueue.main.async {
self.webV.loadRequest(req)
}
} catch {
print("Something went wrong")
}
}
Printing document directory:
[file:///private/var/mobile/Containers/Data/Application/1CC5FFEA-DF9A-4590-8628-B9873F775568/Documents/data_zip/, file:///private/var/mobile/Containers/Data/Application/1CC5FFEA-DF9A-4590-8628-B9873F775568/Documents/data_zip.zip]
Receiving this error code in console: NSURLConnection finished with error - code -1100
Can anyone help me with this API code. I got everything but one error fixed.
Here is my code:
let APIUrl = NSURL(string:"https://api.openweathermap.org/data/2.5/weather? lat=35&lon=150&appid=e7b2054dc37b1f464d912c00dd309595&units=Metric")
var request = URLRequest(url:APIUrl! as URL)
let task = URLSession.shared.dataTask(with: request as URLRequest)
guard let data = Data else {return}
let decoder = JSONDecoder()
let weatherData = try decoder.decode(MyWeather, from: data)
let ggtemp = weatherData.main?.temp
print(ggtemp, "THIS IS THE TEMP")
DispatchQueue.main.async {
tempDisplay.text = String (ggtemp) + " c"
}
}
Image of error
Once I fix the "let data = data" error, I get an error on the "let task = URLSesss..."
Any help would be appreciated. Thanks in advance.
Try this code
let APIUrl = NSURL(string:"https://api.openweathermap.org/data/2.5/weather?lat=35&lon=150&appid=e7b2054dc37b1f464d912c00dd309595&units=Metric")
var request = URLRequest(url:APIUrl! as URL)
request.httpMethod = "GET"
let dataTask = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error ?? "Error is empty.")
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse ?? "HTTP response is empty.")
}
guard let responseData = data else {
print("Error: did not receive data")
return
}
do {
let weatherData = try JSONDecoder().decode(MyWeather.self, from: responseData)
let ggtemp = weatherData.main?.temp
print(ggtemp, "THIS IS THE TEMP")
DispatchQueue.main.async {
tempDisplay.text = String (ggtemp) + " c"
}
} catch {
print("error parsing response from POST on /todos")
return
}
})
dataTask.resume()
This question already has answers here:
How to write a file to a folder located at Apple's Files App in Swift
(2 answers)
Closed 3 years ago.
I tried downloading pdf files with the below code. Here it's storing in the app data. But I need to show the downloaded pdf in "Files" folder in iPhone.
// Create destination URL
let documentsUrl:URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
let destinationFileUrl = documentsUrl.appendingPathComponent("downloadedFile.jpg")
//Create URL to the source file you want to download
let fileURL = URL(string: "http://swift-lang.org/guides/tutorial.pdf")
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)
let request = URLRequest(url:fileURL!)
let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
if let tempLocalUrl = tempLocalUrl, error == nil {
// Success
if let statusCode = (response as? HTTPURLResponse)?.statusCode {
print("Successfully downloaded. Status code: \(statusCode)")
}
do {
try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
} catch (let writeError) {
print("Error creating a file \(destinationFileUrl) : \(writeError)")
}
} else {
print("Error took place while downloading a file. Error description: %#", error?.localizedDescription ?? "");
}
}
task.resume()
Is it possible??
Here's how to download any files and save to Photos(if image file) or Files (if pdf)
let urlString = "your file url"
let url = URL(string: urlString)
let fileName = String((url!.lastPathComponent)) as NSString
// Create destination URL
let documentsUrl:URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
let destinationFileUrl = documentsUrl.appendingPathComponent("\(fileName)")
//Create URL to the source file you want to download
let fileURL = URL(string: urlString)
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)
let request = URLRequest(url:fileURL!)
let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
if let tempLocalUrl = tempLocalUrl, error == nil {
// Success
if let statusCode = (response as? HTTPURLResponse)?.statusCode {
print("Successfully downloaded. Status code: \(statusCode)")
}
do {
try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
do {
//Show UIActivityViewController to save the downloaded file
let contents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
for indexx in 0..<contents.count {
if contents[indexx].lastPathComponent == destinationFileUrl.lastPathComponent {
let activityViewController = UIActivityViewController(activityItems: [contents[indexx]], applicationActivities: nil)
self.present(activityViewController, animated: true, completion: nil)
}
}
}
catch (let err) {
print("error: \(err)")
}
} catch (let writeError) {
print("Error creating a file \(destinationFileUrl) : \(writeError)")
}
} else {
print("Error took place while downloading a file. Error description: \(error?.localizedDescription ?? "")")
}
}
task.resume()
I implemented subscription (auto renewable purchase). I want to check whether the user is still subscribed or not when my app launched ever time. I tried to use the below code but it returns always "success" even if user is not subscribed.
How can I check the user subscription status?
func receiptValidation() {
let SUBSCRIPTION_SECRET = "password"
let receiptPath = Bundle.main.appStoreReceiptURL?.path
if FileManager.default.fileExists(atPath: receiptPath!){
var receiptData:NSData?
do{
receiptData = try NSData(contentsOf: Bundle.main.appStoreReceiptURL!, options: NSData.ReadingOptions.alwaysMapped)
}
catch{
print("ERROR: " + error.localizedDescription)
}
//let receiptString = receiptData?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
let base64encodedReceipt = receiptData?.base64EncodedString(options: NSData.Base64EncodingOptions.endLineWithCarriageReturn)
print(base64encodedReceipt!)
let requestDictionary = ["receipt-data":base64encodedReceipt!,"password":SUBSCRIPTION_SECRET]
guard JSONSerialization.isValidJSONObject(requestDictionary) else { print("requestDictionary is not valid JSON"); return }
do {
let requestData = try JSONSerialization.data(withJSONObject: requestDictionary)
let validationURLString = "https://sandbox.itunes.apple.com/verifyReceipt" // this works but as noted above it's best to use your own trusted server
guard let validationURL = URL(string: validationURLString) else { print("the validation url could not be created, unlikely error"); return }
let session = URLSession(configuration: URLSessionConfiguration.default)
var request = URLRequest(url: validationURL)
request.httpMethod = "POST"
request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringCacheData
let task = session.uploadTask(with: request, from: requestData) { (data, response, error) in
if let data = data , error == nil {
do {
let appReceiptJSON = try JSONSerialization.jsonObject(with: data)
print("success. here is the json representation of the app receipt: \(appReceiptJSON)")
// always through here
} catch let error as NSError {
print("json serialization failed with error: \(error)")
}
} else {
print("the upload task returned an error: \(error)")
}
}
task.resume()
} catch let error as NSError {
print("json serialization failed with error: \(error)")
}
}
}
I am trying to download webcontent for a weather app that I am making. When I run the app the source code on the website does not appear on my Xcode. I also updated my info.plist to accept web content.
Do you have an idea on what the problem is and how I can solve it?
I have a copied my code below:
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string: "http://weather.weatherbug.com/weather-forecast/now/abuja")!
let request = NSMutableURLRequest(url:url as URL)
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil{
print(error.debugDescription)
}
else {
if let unwrappedData = data{
let dataString = NSString(data: unwrappedData, encoding: String.Encoding.utf8.rawValue)
print(dataString as Any)
}
}
}
task.resume()
}
Change your url to use https and it should work.
let url = NSURL(string: "https://weather.weatherbug.com/weather-forecast/now/abuja")!
Here's an example in Swift 4 for downloading a document and parsing as JSON:
// If you're doing this in an Xcode Playground, uncomment these lines:
// import XCPlayground
// XCPSetExecutionShouldContinueIndefinitely()
let url = URL(string: "http://json-schema.org/example/geo.json")!
let task = URLSession.shared.dataTask(with: url) {
data, response, error in
guard error == nil else { return }
guard data != nil else { return }
guard (response as? HTTPURLResponse)?.statusCode == 200 else { return }
do {
if let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any] {
print(json)
}
} catch { return }
}
task.resume()
Use "if let" instead of only "let" and it should work.
if let url = URL(string:"http://weather.weatherbug.com/weather-forecast/now/abuja"){
let request = NSMutableURLRequest(url: url)
let task = URLSession.shared.dataTask(with: request as URLRequest){
data, responds, error in
if error != nil{
print(error!)
} else {
if let unwrappedData = data {
let dataString = NSString(data: unwrappedData, encoding: String.Encoding.utf8.rawValue)
print(dataString!)
DispatchQueue.main.sync(execute: {
})
}
}
}
task.resume()
}
Use
let myURLString = "http://weather.weatherbug.com/weather-forecast/now/abuja"
guard let myURL = URL(string: myURLString) else {
print("Error: \(myURLString) doesn't seem to be a valid URL")
return
}
do {
let myHTMLString = try String(contentsOf: myURL, encoding: .ascii)
print("HTML : \(myHTMLString)")
} catch let error {
print("Error: \(error)")
}
From Link