【问题标题】:Downloading Text From UrL从 UrL 下载文本
【发布时间】:2018-04-27 17:00:10
【问题描述】:

所以我有一个 url 链接,其中包含我想在我的应用程序中显示的内容的文本文件。但是我很难将它下载到我的应用程序中。我试图在该位置获取文本的代码目前看起来像这样

   @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()
    }

消息网址是这个链接

var urlString = "18.218.88.192:8080/ActiveHoneypotWeb/logfiles/159.65.139.103-0-commands.txt"

由于某种原因,它每次都会崩溃。 谁能帮帮我?

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    您对! 的滥用给您带来了很多问题。但问题的最终原因是 18.218.88.192:8080/ActiveHoneypotWeb/logfiles/159.65.139.103-0-commands.txt 不是有效的 URL。没有方案。根据需要在 URL 的开头添加http://https://

    这是您的代码的编写方式。这会正确检查错误和 nil 值。

    @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")
        }
    }
    

    【讨论】:

    • 我改了,还是不行,你能帮我看看我的函数的语法吗
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-23
    • 2011-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多