我是第一次使用 Swift 进行编程,在此过程中我遵循this教程。不幸的是,该教程看起来有点过时,并且大多数代码都会引发构建时错误。最常出现的错误是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()
}
}
}
在 Swift 3.0 中,一些基本类型已经删除了“NS”前缀。在 swift 2.2 的早期,我们曾经有NSUserDefaults
, NSURLSession
, NSFileManager
现在,他们中的大多数都放弃了前缀“NS”并更改为UserDefaults
, URLSession
, FileManager
etc.
您的代码包含许多带有“NS”前缀的类型。只需删除它,您的代码就可以转换为 Swift 3。转换后的代码如下所示:
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
}
}
}
另外,我没有看到任何调用的函数parseJSON()
在你的班级里。我相信你必须添加它。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)