问题
I want to import data from a .csv file, so I have used the CSVImporter https://github.com/Flinesoft/CSVImporter. It works well, but it starts the importing before the other part of the function viewDidLoad is executed.
The following code is only a test but I need either a solution that ensures that the CSVImporter completes importing before the other viewDidLoad code executes or a function which starts automatically after viewDidLoad.
Here is my code:
var Vokabeln: [[String]]?
var i = 0
override func viewDidLoad() {
super.viewDidLoad()
let path = "/Users/---CENSORED---/Documents/TestLöschen/TestLöschen/Vokabeln.csv"
let importer = CSVImporter<[String]>(path: path, delimiter: ";")
importer.startImportingRecords { $0 }.onFinish { importedRecords in
for record in importedRecords {
self.Vokabeln?[self.i][0] = record[0]
self.Vokabeln?[self.i][1] = record[1]
self.Vokabeln?[self.i][2] = record[2]
print("Begin1")
print(record[0])
print(record[1])
print(record[2])
print("End1")
self.i += 1
}
}
print("Begin2")
print(Vokabeln?[0][0])
print(Vokabeln?[0][1])
print(Vokabeln?[0][2])
print(Vokabeln?[1][0])
print(Vokabeln?[1][1])
print(Vokabeln?[1][2])
print("End2")
}
So first it prints "Begin2" and 6 times prints nil. Then, when the function viewDidLoad is finished, it prints "Begin1", then the correct variables and "End1"
Can anybody help me? Thanks.
回答1:
startImportingRecords
works asynchronously, just put the code to print the Vokabeln
in the completion handler after the repeat loop.
First of all you need to initialize the array otherwise nothing will be appended. And do not declare the array as optional and variable names are supposed to start with a lowercase letter.
var vokabeln = [[String]]()
In case to update the UI wrap the code in a dispatch block for example
importer.startImportingRecords { $0 }.onFinish { importedRecords in
for record in importedRecords {
self.vokabeln[self.i][0] = record[0]
self.vokabeln[self.i][1] = record[1]
self.vokabeln[self.i][2] = record[2]
print("Begin1")
print(record[0])
print(record[1])
print(record[2])
print("End1")
self.i += 1
}
DispatchQueue.main.async {
print("Begin2")
print(self.vokabeln[0][0])
print(self.vokabeln[0][1])
print(self.vokabeln[0][2])
print(self.vokabeln[1][0])
print(self.vokabeln[1][1])
print(self.vokabeln[1][2])
print("End2")
}
}
But there is still another issue. If you declare the array as [[String]]
both outer and inner arrays are empty and you cannot assign values with index subscripting. I recommend this syntax
for record in importedRecords {
self.vokabeln.append(record) // this appends the whole record array
print("Begin1")
print(record)
print("End1")
}
PS: Consider to use a more suitable text format like JSON or property list.
来源:https://stackoverflow.com/questions/42860908/csvimporter-starts-importing-after-viewdidload-swift