在Swift中重命名了问题

时间:2017-01-14 06:00:24

标签: swift xcode

我是第一次使用Swift进行编程,并且这样做我跟随this教程。不幸的是,看起来这个教程有点过时了,大部分代码都抛出了Buildtime错误。最重复出现的错误是NSURLSession has been renamed to URLSession。我试过让Swift修复它,但在很多情况下它只是开始发出警告。我也遇到Value type HomeModel has no member'parseJSON'错误以及NSDat is not implicitly convertible to data错误。据我所知,看起来不再使用NSURL,但我不确定其他两个。看到这是我第一次参与的Swift项目,我不知道如何解决这些问题。有人可以提供一些有关如何解决这些错误的见解吗?

这是代码:

import Foundation

protocol HomeModelProtocal: class {
    func itemsDownloaded(items: NSArray)
}


class HomeModel: NSObject, NSURLSessionDataDelegate {

    //properties

    weak var delegate: HomeModelProtocal!

    var data : NSMutableData = NSMutableData()

    let urlPath: String = "http://testurl.com/service.php" //this will be changed to the path where service.php lives


    func downloadItems() {

        let url: NSURL = NSURL(string: urlPath)!
        var session: NSURLSession!
        let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()


        session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)

        let task = session.dataTaskWithURL(url)

        task.resume()

    }

    func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
        self.data.appendData(data);

    }

    func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
        if error != nil {
            print("Failed to download data")
        }else {
            print("Data downloaded")
            self.parseJSON()
        }

    }
}

1 个答案:

答案 0 :(得分:1)

几种基本类型在Swift 3.0中删除了“NS”前缀。早在swift 2.2中,我们曾经有NSUserDefaultsNSURLSessionNSFileManager等等。现在,他们中的大多数都删除了前缀“NS”并更改为UserDefaults,{{ 1}},URLSession等。

您的代码包含许多带有“NS”前缀的类型。只需删除它,您的代码就可以转换为Swift 3.您转换后的代码如下所示:

FileManager

另外,我没有在你的班级中看到任何名为protocol HomeModelProtocal: class { func itemsDownloaded(items: NSArray) } class HomeModel: NSObject, URLSessionDataDelegate { //properties weak var delegate: HomeModelProtocal! var data : Data = Data() let urlPath: String = "http://testurl.com/service.php" //this will be changed to the path where service.php lives func downloadItems() { let url: URL = URL(string: urlPath)! var session: URLSession! let configuration = URLSessionConfiguration.default session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil) let task = session.dataTask(with: url) task.resume() } func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { self.data.append(data); } func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { if error != nil { print("Failed to download data") }else { print("Data downloaded") self.parseJSON() // This class doesn't have a function parseJSON(). So, it's giving you an error like this } } } 的函数。我相信你必须加上它。