更新
我在 Login.swift 中的 POST 请求返回我希望映射到 Particulars.swift 中的变量(例如 API 令牌)的值,并通过扩展写入领域。我该怎么做呢?
我的 Login.swift 代码:
import Foundation
import Alamofire
import SwiftyJSON
import RealmSwift
import ObjectMapper
import AlamofireObjectMapper
class Login {
init(userName: String, passWord: String) {
Data.sharedInstance.userName = userName
Data.sharedInstance.passWord = passWord
}
// call this method to login
func getRequest() {
Alamofire.request(.POST, Data.todoEndpoint, parameters: ["username": Data.sharedInstance.userName!, "password": Data.sharedInstance.passWord!])
.responseJSON { response in
if let result = response.result.value
{
let value = JSON(result)
if let api_key = value["api_token"].string
{
print("The token is " + api_key)
}
else
{
print("error parsing api token")
}
}
else
{
print("JSON data is nil.")
}
}
}
}
我正在尝试将我的 JSON 请求映射到领域,但我一直被抛出此错误
无法推断通用参数“T”
这就是我要找的:(都在单独的文件中)
发送 GET 请求 -> 存储在领域/如果新对象不存在则创建新对象/更新对象
我该如何解决?
调用 GET 请求的 代码(完整代码在这里https://codeshare.io/l4cEQ)
FetchData.get(Particulars.self, success: {
print("success!!!")
}) {
print("fail!!!")
}
处理 GET 请求的代码
import Foundation
import Alamofire
import ObjectMapper
import AlamofireObjectMapper
import RealmSwift
class FetchData {
static func get <T:Object where T:Mappable,T:Meta> (type:T.Type,success:()->Void,fail:()->Void)->Void {
Alamofire.request(Method.GET, type.url())
.responseArray { (response: Response<[T], NSError>) in
switch response.result {
case .Success:
let items = response.result.value
if let items = items {
let realm = try! Realm()
try! realm.write {
for item in items {
realm.add(item, update: true)
}
}
success()
}
case .Failure(_):
fail()
break
}
}
}
}
映射对象的代码(Particulars.swift)
import Foundation
import RealmSwift
import ObjectMapper
protocol Meta {
static func url()->String
}
class Particulars: Object, Mappable {
dynamic var name = ""
dynamic var email = ""
dynamic var id = 0
dynamic var profilePicture = ""
dynamic var username = ""
dynamic var apiToken = ""
override static func primaryKey() -> String? {
return "id"
}
//Impl. of Mappable protocol
required convenience init?(_ map: Map) {
self.init()
}
func mapping(map: Map) {
id <- map["id"]
name <- map["name"]
email <- map["email"]
profilePicture <- map["profile_picture"]
username <- map["username"]
apiToken <- map["api_token"]
}
//Impl. of Meta protocol
static func url()->String {
return "https://bitbucket.org/hyphe/blog-examples/raw/master/fetchData/demoapi/books"
}
}