我是IOS开发的新手,我最近尝试realm
问题是,我必须从json文件中获取url然后我将这些url作为对象放入领域...每当我再次启动我的应用程序时,URL变量将从领域获得受尊重的URL ...
像这样:
getUrls()
let realm = try! Realm()
// Query Realm for all dogs less than 2 years old
let urls = realm.objects(UrlCollector.self).first
let sss = realm.objects(UrlCollector.self)
print("no of objects in did load \(sss.count)")
loginUrl = urls!.login
print("login url inside didload \(loginUrl)")
但问题是getUrls
方法......它使用almofire
getUrls
方法:
Alamofire.request("<<<myurl>>>", method: .post, encoding: JSONEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
if let data = response.result.value{
print(data)
let data = JSON(data)
for item in data["result"].arrayValue {
let url = UrlCollector()
url.login = "\(self.server)\(item["login"].stringValue)"
print(url.login)
url.changePassword = "\(self.server)\(item["changePassword"].stringValue)"
print(url.changePassword)
url.phoneNumberVerify = "\(self.server)\(item["phoneNumberVerify"].stringValue)"
print(url.phoneNumberVerify)
url.sessionCheck = "\(self.server)\(item["sessionCheck"].stringValue)"
print(url.sessionCheck)
// Get the default Realm
let realm = try! Realm()
var urls = realm.objects(UrlCollector.self)
// Persist your data easily
try! realm.write {
realm.delete(urls)
realm.add(url)
}
// Query Realm for all dogs less than 2 years old
urls = realm.objects(UrlCollector.self)
print(urls.count)
}
}
break
case .failure(_):
print("Error message:\(response.result.error)")
break
}
}
}
此代码在加载时运行
我的日志:
no of objects in did load 1
login url inside didload
{
result = (
{
changePassword = "/iust_app/android/passwordChange.php";
login = "/iust_app/android/login.php";
phoneNumberVerify = "/iust_app/android/onNumberVerification.php";
sessionCheck = "/iust_app/android/sessionCheck.php";
}
);
}
/iust_app/android/login.php
/iust_app/android/passwordChange.php
/iust_app/android/onNumberVerification.php
/iust_app/android/sessionCheck.php
1
print("no of objects in did load \(sss.count)")
loginUrl = urls!.login
print("login url inside didload \(loginUrl)")
正如您可以在请求之前看到这些运行...请阅读我的日志行以了解
答案 0 :(得分:0)
所有网络请求都是异步执行的。如果您希望在从服务器获得响应后执行代码,请将其放入此请求的完成处理程序中。