I've configured background tasks successfully on my app where a function would directly call a URL and process the data but I've recently changed this so that the function calls the URL, saves to documentsDirectory then processes the data. Since I've updated this my background tasks no longer fire.
I've tried wrapping the functions in a Task after a suggestion on a previous question here but I can't get the Background Task to fire/complete fully. Sometimes it will just print run the print, other times it will just re-schedule the next update and sometimes it will print & schedule but the task never seems to run. Any help would be much appreciated. Thanks!
Update 27/06:
I've done some more troubleshooting on this since posting and it looks like the issue isn't with the task running but it is the app not handling let (url, response) = try await session.download(for: request) within the function in the background task.
This functions as expected within the app, but fails to complete when its a background task. Are there any additional steps or config changes needed to have this run as a background task? Cheers
BG Processing Task:
func handleAppRefresh(task: BGProcessingTask) {
//Schedules another refresh
scheduleAppRefresh()
Task.detached {
do {
print("BGTask fired")
let events = try await BGloadCSV(from: "Eventtest")
print(events)
} catch {
print(error)
}
}
print("handleAppRefresh fired")
}
Function to run:
func BGloadCSV(from csvName: String) async throws -> [CSVEvent] {
var csvToStruct = [CSVEvent]()
// Creates destination filepath & filename
let documentsUrl:URL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL?)!
let destinationFileUrl = documentsUrl.appendingPathComponent("testcsv.csv")
//Create URL to the source file to be downloaded
let fileURL = URL(string: "https://example.com/testcsv.csv")!
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)
let request = URLRequest(url:fileURL)
let (url, response) = try await session.download(for: request)
if let statusCode = (response as? HTTPURLResponse)?.statusCode {
print("File downloaded Successfully. Response: \(statusCode)")
}
let _ = try FileManager.default.replaceItemAt(destinationFileUrl, withItemAt: url)
let data = readCSV(inputFile: "testcsv.csv")
var rows = data.components(separatedBy: "\n")
rows.removeFirst()
// Iterates through each row and sets values
for row in rows {
let csvColumns = row.components(separatedBy: ",")
let csveventStruct = CSVEvent.init(raw: csvColumns)
csvToStruct.append(csveventStruct)
}
print("LoadCSV has run and created testcsv.csv")
pullData(events: csvToStruct)
return csvToStruct
}
I was able to re-create the URLSession into a background task with help from this article & Sample project provided.
https://www.ralfebert.com/ios-examples/networking/urlsession-background-downloads/
Hopefully it helps someone else in the future.
Related
I recently updated to actix web 4, I had some tests that used the actix-web test module that stopped working as expected in the process. I'm sure it's something simple but I'm having trouble figuring out what changed. Here is a minimal example of the issue:
use actix_web::{test, web, App, HttpResponse, HttpRequest};
#[actix_rt::test]
async fn says_hello() {
let req = test::TestRequest::get().uri("/index.html").to_request();
let mut server =
test::init_service(App::new().service(web::scope("/").route("index.html", web::get().to(|_req: HttpRequest| async {
println!("Hello?");
HttpResponse::Ok()
})))).await;
let _resp = test::call_and_read_body(&mut server, req).await;
}
running this test I would expect to see "Hello?" output to my console, however, the request handler function I have defined at "/index.html" doesn't seem to be called and I receive no output.
To be clear, the tests are more complicated and have assertions etc, this is just a working example of the main issue I am trying to resolve
actix-web = { version = "4.1.0", default-features = false }
note:
if I change all paths to the root path it will call the handler, I.E.
let req = test::TestRequest::get().uri("/").to_request();
let mut server =
test::init_service(App::new().service(web::scope("/").route("/", web::get().to(|_req: HttpRequest| async {
println!("Hello?");
HttpResponse::Ok()
})))).await;
let _resp = test::call_and_read_body(&mut server, req).await;
// prints "Hello?" to the console
However no other route combination I have tried calls the request handler.
Rust tests capture the output and only output them for failed tests.
If you want to show output on all tests you have to tell them to do so with either testbinary --nocapture or cargo test -- --nocapture.
I was able to make things work by changing the path in the scope to an empty string
let req = test::TestRequest::get().uri("/index.html").to_request();
let mut server =
test::init_service(App::new().service(web::scope("").route("index.html", web::get().to(|_req: HttpRequest| async {
println!("Hello?");
HttpResponse::Ok()
})))).await;
let _resp = test::call_and_read_body(&mut server, req).await;
// prints "Hello?"
I’m quite new to postman (and coding) and was trying to find and piece together many snippets of scripts to make it work the way I want.
What I want is very simple: I have a list of IDs that I want to make a POST in each of them, get one of the responseBody as a variable and do another POST. I think I’m close but I can’t manage to get it to work.
I’ve tried:
Two POST request in the same Collection and running the collection.
In the first request I have a POST to
https://APIADDRESS/?order_id{{orderid}}&contract[copy_order_data]=true
On the Pre-request Script tab:
var orderids = pm.environment.get(“orderids”);
if (!orderids) {
orderids = [“bc46bf79-2846-44ed-ac4d-78c77c92ccc8”,“81aacc33-1ade-41a3-b23e-06b03b526b8f”];
}
var currentOrderId = orderids.shift();
pm.environment.set(“orderid”, currentOrderId);
pm.environment.set(“orderids”, orderids);
On the Tests tab:
var orderids = pm.environment.get(“orderids”);
if (orderids && orderids.length > 0) {
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable(“invoice.id”, jsonData.invoice.id);
postman.setNextRequest(“Create invoice”);
} else {
postman.setNextRequest(null);
}
invoice.id is a environment variable populated with the response body of the first action/post and then using the variable on the second action/post.
And then the second request would be a POST to
https://APIADDRESS/invoices/{{invoice.id}}/finalize.json
Of course this doesn’t work. Either it doesn't run the second request in the collection or it doesn't do the loope to more than 1 ID on the list.
So I thought that putting the second POST inside the first one would solve it. But I had no luck.
Can please someone help me?
I have tried mentioned use case with sample API's provided by POSTMAN.
Can you try it?
First POST Method Request : https://postman-echo.com/post
Pre-request Script of first POST method
var orderids = pm.environment.get("orderids");
if(!orderids ){
orderids = ["bc46bf79-2846-44ed-ac4d-78c77c92ccc8","81aacc33-1ade-41a3-b23e-06b03b526b8f"];
}
var currentOrderId = orderids.shift();
pm.environment.set("orderid", currentOrderId);
pm.environment.set("orderids", orderids);
Tests Tab of first POST Method
var orderids = pm.environment.get("orderids");
if (orderids && orderids.length > 0) {
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("invoice.id", jsonData.headers.host);
postman.setNextRequest("Test1");
} else {
postman.setNextRequest(null);
}
Second POST Method Reqeust: https://postman-echo.com/post?key={{invoice.id}}
After executing the above collection it will set orederids and invoice.id value in environment variables and then it will call next POST Method.
Hope this will help you.
Thanks #HalfBloodPrince, from the Postman Echo it worked but in my case it doesn't :S
What I manage to get it working was using a Json file as a list of Orderids.
In that case I've separated all requests.
Request1 - https://APIADDRESS/?order_id{{orderid}}&contract[copy_order_data]=true
Tests tab:
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("invoice.id", jsonData.invoice.id);
Request2 - https://APIADDRESS/invoices/{{invoice.id}}/finalize.json
That way everything is in a neat and organized way.
Thanks
I want to save and retrieve the password and userAccount in keychain. I found a solution in stackoverflow and I use the code there. Save and Load from KeyChain | Swift. But this code only saves and load the password not the accountName. I think I figured out how to save the accountName but I need to figure out how to load it along with the password. Here is the code to save you some time from going into that link.
var userAccount = "AuthenticatedUser"
let accessGroup = "SecurityService"
// Mark: User defined keys for new entry
// Note: add new keys for new secure item and use them in load and save methods
let accountKey = "KeyForAccount"
let passwordKey = "KeyForPassword"
private class func save(service: String, data: String) {
let dataFromString: NSData = data.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue), allowLossyConversion: false)! as NSData
//Instantiate a new default keychain query
let keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, service, userAccount, dataFromString], forKeys: [kSecClassValue, kSecAttrServiceValue as NSCopying, kSecAttrAccountValue as NSCopying, kSecValueDataValue as NSCopying])
//Add new keychain item
let status = SecItemAdd(keychainQuery as CFDictionary, nil)
if status != errSecSuccess { //Always check status
print("Write failed. Attempting update.")
//updatePassword(token: data)
}
}
private class func load(service: String) -> String? {
//Instantiate a new default keychain query
//Tell the query to return a result
//Limit our results to one item
let keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, service, userAccount, kCFBooleanTrue, kSecMatchLimitOneValue], forKeys: [kSecClassValue, kSecAttrServiceValue as NSCopying, kSecAttrAccountValue as NSCopying, kSecReturnDataValue as NSCopying, kSecMatchLimitValue as NSCopying])
var dataTypeRef: AnyObject?
//Search for the keychain items
let status : OSStatus = SecItemCopyMatching(keychainQuery, &dataTypeRef)
var contentsOfKeychain: String? = nil
if status == errSecSuccess {
if let retrieveData = dataTypeRef as? Data {
contentsOfKeychain = String(data: retrieveData as Data, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
}
} else {
print("Nothing was retrieved from the keychain. Status code \(status)")
}
print(contentsOfKeychain ?? "none found")
return contentsOfKeychain
}
Complete code is inside the link. Thanks all.
But this code only saves and load the password not the accountName.
The code you show doesn't save or load the password or the account name.
What you have are two functions, one to save a key/value pair, one to load a key's value. It is how you call these two functions that determines what gets saved/loaded.
Somewhere in your code you call save to save the password, you need to call save (using a different key) to save the account name as well. Likewise for load. Your code does define the two keys to use (accountKey & passwordKey).
HTH
I'm newbie, plz help me to solve this out, I still have lots of other things to work on, really thank you thank you very much!
This is a further question after How to use FMDB on the generic iOS device instead of simulator?
When I execute the app on my device and the error threw out: "no such table: Student info", I've print all the path and they all pointed to the same file so I assumed the database has already copied? Console shows like this:
file:///var/mobile/Containers/Data/Application/B5E42F3C-524E-4BBF-8667-1EED0C963A77/Documents/
file:///var/mobile/Containers/Data/Application/B5E42F3C-524E-4BBF-8667-1EED0C963A77/Documents/Data.db
/var/mobile/Containers/Data/Application/B5E42F3C-524E-4BBF-8667-1EED0C963A77/Documents/Data.db
file:///var/mobile/Containers/Data/Application/B5E42F3C-524E-4BBF-8667-1EED0C963A77/Documents/
file:///var/mobile/Containers/Data/Application/B5E42F3C-524E-4BBF-8667-1EED0C963A77/Documents/Data.db
/var/mobile/Containers/Data/Application/B5E42F3C-524E-4BBF-8667-1EED0C963A77/Documents/Data.db
/var/mobile/Containers/Data/Application/B5E42F3C-524E-4BBF-8667-1EED0C963A77/Documents/Data.db
<NSFileManager: 0x17401c1b0>
2017-03-13 16:43:25.446039 Test1.3[16360:5045427] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /private/var/containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles
2017-03-13 16:43:25.457278 Test1.3[16360:5045427] [MC] Reading from public effective user settings.
Insert failed:
Optional("no such table: Student info")
The Data.db is in my bundle resources in target; and the contents in my device is a blank Data.db;
The 2nd question: If you look at the Utility.Swift in the previous question, although the app works good on simulator but after it was loaded, there should be an alertView said "Your database copy successfully", but it didn't. Following is that part of the code:
class func copyFile(_ fileName: NSString){
let dbPath: String = getPath(fileName as String)
let fileManager = FileManager.default
print(dbPath)
print(fileManager)
if !fileManager.fileExists(atPath: dbPath) {
let documentsURL = Bundle.main.resourceURL
let fromPath = documentsURL!.appendingPathComponent(fileName as String)
var error : NSError?
do {
try fileManager.copyItem(atPath: fromPath.path, toPath: dbPath)
}
catch let error1 as NSError {
error = error1
}
if(error != nil){
self.invokeAlertMethod("Error Occured", strBody: "\(error?.localizedDescription)" as NSString, delegate: nil)
}
else{
self.invokeAlertMethod("Successed", strBody: "Your database copy successfully", delegate: nil)
}
}
}
Okay for answering this question I went through your demo.
Where I found couple of mistakes. Let me go through one by one.
1) Your class Utility have a getPath method. What it does it will
keep copying db every time although db is already present in documents
directory and your documents directory db will be replaced with the sample structure. You should always check that if db is already present in documents directory or not.
2) Your db was getting copied into documents directory but structure
wasn't. There was no Student info table in db of documents directory.
3) Please avoid using space or any special characters in table names.
So what I did just corrected your method getPath in utility class.
Please replace your method with this one
class func getPath(_ fileName: String) -> String {
let bundlePath = Bundle.main.path(forResource: "Data", ofType: ".db")
let destPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let fileManager = FileManager.default
let fullDestPath = URL(fileURLWithPath: destPath).appendingPathComponent("Data.db")
if fileManager.fileExists(atPath: fullDestPath.path){
print("Database file is exist")
print(fileManager.fileExists(atPath: bundlePath!))
}else{
do{
try fileManager.copyItem(atPath: bundlePath!, toPath: fullDestPath.path)
}catch{
print("\n",error)
}
}
print(fullDestPath.path)
return fullDestPath.path
}
After changing this piece of code I tried to run in my device and inserted couple of records.
Let me know if you have any more questions.
If you find this answer helpful just accept it.
First trying delete your app and then reinstall it.
OR
I have created a project over FMDB in Swift which you can use to solve your issue. FMDB Wrapper class you can use in Objective C project as well.
https://github.com/LalitKY/Swift-FMDB
Hope this helps.
I'm a Swift beginner and I'm trying to figure out how to retrieve text from a web article, create a new text file and save the text data into it (Using Swift Playgrounds). Is this possible?
The only thing I could find online regarding the subject was this, and I don't think it is even written for Swift 3:
P.S. If my question needs more details, please let me know instead of putting it on hold. Thanks!
import Cocoa
var url = NSURL(string: "http://finance.yahoo.com/news/tv-news-ces-2017-120931816.html")
if url != nil {
let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
print(data)
if error == nil {
var urlContent = NSString(data: data, encoding: NSUTF8StringEncoding) as NSString!
print(urlContent)
That's Swift 2.3. In Swift 3 use URL instead of NSURL and use URLSession rather than NSURLSession, etc. You'd also use String rather than NSString. E.g.
let url = URL(string: "http://finance.yahoo.com/news/tv-news-ces-2017-120931816.html")!
let task = URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data, error == nil else {
print("\(error)")
return
}
let string = String(data: data, encoding: .utf8)
print("\(string)")
}
task.resume()
If you're going to do this in a playground, remember that this runs asynchronously, so you'll need to set needsIndefiniteExecution.
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
To actually parse the HTML, you should consider using a HTML parser like TFHpple (written in Objective-C, but still works great from Swift) or NDHpple (a Swift version, in which I don't have as much confidence as TFHpple, but probably would work fine).
You might want to see How to Parse HTML on iOS. It's dated, but walks you through the concepts (making sure you're not violating ToS of the web site, how to use the parsers, etc.).
If you want to save this to a file, you can do something like:
let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
.appendingPathComponent("test.dat")
try! data.write(to: fileURL)
You can use whatever file extension you want.