在swift中从dropbox读取并解析文件



我正在学习如何在swift中从dropbox读取和解析csv文件的教程。然而,本教程已有4年历史,我的代码不是用swift5编译的。代码示例复制在下面,原始视频教程的链接在这里https://www.youtube.com/watch?v=O6AKHAXpji0

我犯了两个错误。

错误1:

在callFileFromWeb((的let请求=行上{}

'NSURL' is not implicitly convertible to 'URL'; did you mean to use 'as' to explicitly convert?

错误2:

并且在let会话=。。。在httpGet(({}中

'NSURLSession' has been renamed to 'URLSession'

当我试图实现对错误二的修复时,我得到了另一个错误

Cannot call value of non-function type 'URLSession`

有什么想法吗?为了在swift5中工作,我应该调整什么?


var items:[(days:String, city:String, inches: String)]?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
callFileFromWeb()
}
func callFileFromWeb(){
let request = NSMutableURLRequest(URL: NSURL(string: "https://dl.dropboxusercontent.com/u/2813968/raindata.txt")!)
httpGet(request){
(data, error) -> Void in
if error != nil {
print(error)
} else {
print(data)//PRINTING ALL DATA TO CONSOLE
let delimiter = ":"

self.items = []
let lines:[String] = data.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) as [String]


for line in lines {
var values:[String] = []
if line != "" {
values = line.componentsSeparatedByString(delimiter)
// Put the values into the tuple and add it to the items array
print(values[2])//PRINTING LAST COLUMN
let item = (days: values[0], city: values[1], inches: values[2])
self.items?.append(item)
}}//all good above
//  self.AddDataToDatabase()
}//there was an error

}//end of request

}//end of get data from web and load in database


func httpGet(request: NSURLRequest!, callback: (String, String?) -> Void) {
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request){
(data, response, error) -> Void in
if error != nil {
callback("", error!.localizedDescription)
} else {
let result = NSString(data: data!, encoding:
NSASCIIStringEncoding)!
callback(result as String, nil)
}
}
task.resume()
}


最终目标是能够从投递箱中读取文件。文件更新较弱,因此当用户启动应用程序时,他们总是可以访问文件的最新版本,而不必在文件更新时重新下载应用程序。这是正确的方法吗?

在过去分析CSV文件的项目中证明有用的框架是:

CSwiftV->https://github.com/Daniel1of1/CSwiftV

更新时间:2020年9月23日

让我通过重构callFileFromWeb():来演示它

func callFileFromWeb() {
let dropboxURL = URL(string: "https://dl.dropboxusercontent.com/u/2813968/raindata.txt")
URLSession.shared.dataTask(with: dropboxURL!) { data, response, error in 
guard let urlData = data, error == nil else {
return
}
let unparsedCSV = String(data: urlData, encoding: String.Encoding.utf8) ?? "Year,Make,Model,Description,Pricern1997,Ford,E350,descrition,3000.00rn1999,Chevy,Venture,another description,4900.00rn"
let csv = CSwiftV(with: unparsedCSV)
let rows = csv.rows
var iteration = 0
for row in rows {
// Assuming you want the last row
if iteration == rows.count - 1 {
let item = (days: row[0], city: row[1], inches: row[2])
self.items?.append(item)
}
iteration += 1
}
}
}

还有一件事,请记住,您需要从Github下载CSSwiftV,并将原始CSwiftV.swift文件复制到您的项目中。

希望这能有所帮助!

最新更新