Ios 从UrL下载文本
因此,我有一个url链接,其中有一个文本文件,其中包含我想在我的应用程序中显示的内容。然而,我有一个非常困难的时间下载到我的应用程序。我试图在该位置抓取文本的代码当前如下所示Ios 从UrL下载文本,ios,swift,Ios,Swift,因此,我有一个url链接,其中有一个文本文件,其中包含我想在我的应用程序中显示的内容。然而,我有一个非常困难的时间下载到我的应用程序。我试图在该位置抓取文本的代码当前如下所示 @objc func grabTextFile(){ let messageURL = URL(string: urlString) let sharedSession = URLSession.shared let downloadTask: URLSessionDo
@objc func grabTextFile(){
let messageURL = URL(string: urlString)
let sharedSession = URLSession.shared
let downloadTask: URLSessionDownloadTask = sharedSession.downloadTask(with: messageURL!,completionHandler: {
(location: URL!, response: URLResponse!, error: NSError!) -> Void in
var urlContents = ""
do{
urlContents = try String(contentsOf: location, encoding: String.Encoding.utf8)
}catch {
urlContents = ""
}
print(urlContents)} as! (URL?, URLResponse?, Error?) -> Void)
downloadTask.resume()
}
消息url就是这个链接
var urlString=“18.218.88.192:8080/ActiveHoneypotWeb/logfiles/159.65.139.103-0-commands.txt”
由于某种原因,它每次都会崩溃。
有人能帮我吗?你误用了
代码>会给您带来很多问题。但问题的最终原因是18.218.88.192:8080/ActiveHoneypotWeb/logfiles/159.65.139.103-0-commands.txt
不是有效的URL。没有计划。根据需要将http://
或https://
添加到URL的开头
下面是应该如何编写代码。这将正确检查错误和零值
@objc func grabTextFile(){
if let messageURL = URL(string: urlString) {
let sharedSession = URLSession.shared
let downloadTask = sharedSession.downloadTask(with: messageURL) { (location, response, error) in
var urlContents = ""
if let location = location {
do{
urlContents = try String(contentsOf: location, encoding: String.Encoding.utf8)
}catch {
print("Couldn't load string from \(location)")
}
} else if let error = error {
print("Unable to load data: \(error)")
}
}
downloadTask.resume()
} else {
print("\(urlString) isn't a valid URL")
}
}
我改变了它,但仍然不起作用。你能帮我修改一下函数的语法吗