How to load data in the collectionview from JSON to Swift by using Alamofire and Kingfisher - swift

I need to get the data from already made JSON file to the Swift. By using MVVM desing I wrote this code in the Repo class
func loadFoods() {
AF.request("http://example.com/foods/getAllFoods.php",method: .get).response { response in
if let data = response.data {
do{
let result = try JSONDecoder().decode(ProductsResponse.self, from: data)
if let list = result.foods {
self.foodList.onNext(list)
}
}catch{
print(error.localizedDescription)
}
}
}
}
Here's the code from View Model class:
class HomeViewModel {
var foodList = BehaviorSubject <[Foods]>(value: [Foods]())
var frepo = FoodsDaoRepository()
init() {
loadFoods()
foodList = frepo.foodList
}
func loadFoods() {
frepo.loadFoods()
}
func loadPersons(){
prepo.loadPersons()
}
and I wrote this code in the ViewContoller class:
override func viewDidLoad() {
super.viewDidLoad()
searchTextField.delegate = self
collectionView.delegate = self
collectionView.dataSource = self
let _ = viewModel.foodList.subscribe(onNext: { list in
self.foodsList = list
DispatchQueue.main.async {
self.collectionView.reloadData()
}
})
override func viewWillAppear(_ animated: Bool) {
viewModel.loadFoods()
}
Foodlist variable takes the data from Food class:
class Foods: Codable {
var id : Int?
var name : String?
var image : String?
var price : Int?
var category : String?
init(id: Int?, name: String?, image: String?, price: Int?, category: String?) {
self.id = id
self.name = name
self.image = image
self.price = price
self.category = category
}
}
But it didn't help to get the data from JSON to the CollectionView. It just shows empty collection view cells.
Also how can I get an image by using Kingfisher and Alamofire?
I tried to explain the problem and wrote a code to expand my question

Related

How to search by API OpenWeatherApi city?

I created these requests, I don’t know if I asked them correctly. If someone can tell, they will be grateful. Here is my code. I need to search for a city in the search and so that the weather is displayed in the table. Please help and tell me how to set and where to fix it. Or did I set the functions and methods incorrectly? error
"The data couldn’t be read because it is missing."
import UIKit
class SearchViewController: UIViewController,UISearchResultsUpdating, UITableViewDelegate,UITableViewDataSource {
#IBOutlet weak var searchBar: UISearchBar!
#IBOutlet weak var tableView: UITableView!
var filteredCity: [OpenWeather] = []
// var searchCity: [OpenWeather]=[]
let wetherApi = WeatherManager()
var cityWeather = [OpenWeather]()
let netSer = NetworkService()
let searchController = UISearchController()
var isSearchBarEmpty: Bool {
return searchController.searchBar.text?.isEmpty ?? true
}
override func viewDidLoad() {
super.viewDidLoad()
searchController.searchResultsUpdater = self
navigationItem.searchController = searchController
tableView.delegate = self
tableView.dataSource = self
wetherApi.fetchCurrentWeather(city: "London")
}
func updateSearchResults(for searchController: UISearchController) {
self.filteredCity = self.cityWeather.filter { (city:OpenWeather) -> Bool in
if city.city.lowercased().contains(self.searchController.searchBar.text!.lowercased()){
return true
}else {
return false
}
}
//Update the results TableView
self.tableView.reloadData()
}
#objc func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cityWeather.count
}
#objc(tableView:cellForRowAtIndexPath:) internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CityTableViewCell
cell.cityTemp.text = cityWeather[indexPath.row].city
cell.cityTemp.text = "\(cityWeather[indexPath.row].main.tempCelsius)"
return cell
}
}
My structure weather:
import Foundation
import UIKit
struct OpenWeather: Codable {
let coord:Coordinate
let city:String
let weathertwo:[WeatherTwo]
let main: Main
}
struct Coordinate: Codable {
let lan:Float
let lot:Float
enum CodingKeys: String, CodingKey {
case lan = "lat"
case lot = "lon"
}
}
struct WeatherTwo: Codable {
let main: String
let description: String
}
struct Main: Codable {
private let temp: Double
var tempCelsius: Double {
get {
return (temp - 32) / 1.8
}
}
private let temp_min: Double
var tempCelsiusmin: Double {
get {
return (temp - 32) / 1.8
}
}
private let temp_max: Double
var tempCelsiusmax: Double {
get {
return (temp - 32) / 1.8
}
}
let pressure: Int
let humidity: Int
}
My code Api codable download:
struct WeatherManager {
//Deliberately deleted "q=London" within the url, because it needs to be customizable with a different city
func fetchCurrentWeather(city: String){
let URL_API = "https://api.openweathermap.org/data/2.5/weather?q="
let CITY_ID = city
//let URL_API_KEY = "<api_key>"
let session = URLSession(configuration: .default)
let urlString = URL_API + CITY_ID + "&appid=cfe547d810fc4ad95e8f24187c6b08da"
guard let url = URL(string: urlString) else {
print("Error building URL")
return
}
let task = session.dataTask(with: url) { (data, response, error) in
DispatchQueue.main.async {
if let error = error {
print(error.localizedDescription)
return
}
guard let data = data, let response = response as? HTTPURLResponse else {
print("Invalid data or response")
return
}
do {
if response.statusCode == 200 {
let items = try JSONDecoder().decode(OpenWeather.self, from: data)
print(items)
} else {
print("Response wasn't 200. It was: " + "\n\(response.statusCode)")
}
} catch {
print(error.localizedDescription)
}
}
}
task.resume()
}
}
I see a few reasons this happens.
If you look at the response the API gives you, you will find that:
The keys weathertwo and city do not exist in the response, yet they are present in your OpenWeather struct. You need to make them optional or provide your default values by overriding the init if you don't always expect this data to be present
Have a look at the coord object in the response
"coord": {
"lon": -0.1257,
"lat": 51.5085
}
Compare the spelling of keys with your coord struct:
struct Coordinate: Codable {
let lan:Float
let long:Float
}
If you want to use different variable names, you need to look at using CodingKeys
However, the simplest fix I believe is changing your OpenWeather struct to this:
struct OpenWeather: Codable {
let coord: Coordinate
let city: String?
let weathertwo: [WeatherTwo]?
let main: Main
}
and fixing coords to this:
struct Coordinate: Codable {
let lat: Float
let lon: Float
}
should get rid of the error and give you the data you need as I can see data from the Open Weather API printed on the console:
OpenWeather(coord: TestApp.Coordinate(lat: 25.2582, lon: 55.3047), city: nil, weathertwo: nil, main: TestApp.Main(temp: 300.38, temp_min: 299.31, temp_max: 301.29, pressure: 1008, humidity: 54))
There are other improvements that could be made such as using camel case for the variables with CodingKeys but that is something you can decide later.
Give this a go and see if it resolves your issue.
Update
As you rightly pointed out, you asked how to get the list of cities supported by Open Weather.
I had a quick look, it does not look like they have an API to get a list of all the cities. Their API seems to support you sending a city name and it will send back to you the weather data for that city.
However, they provide their list of cities here
I think the file history.city.list.json.gz has all the city data which might need to be included in your app or somewhere online if you wish.
Have a look.

[Core Data]: data: <fault>

The questions parameter in the function is full, but I cannot transfer assignments to questionsCD.questions?.questionList.
The id and title variables are not nil. Those variables are working in a healthy way.
In Console output, questions return nil.
I cannot assign the questionList variable in the QuestionsNSSecureCoding class, so I think it returns nil. Why ?
You can examine the Core Data Entity image to see the questionsCD.questions?.questionList in more detail.
Core Data Save Function:
func saveSelectedQuestion(questionTitle: String, id: String, questions: [QuestionList]) {
let questionsCD = QuestionCD(context: persistentContainer.viewContext)
questionsCD.title = questionTitle
questionsCD.id = id
questionsCD.questions?.questionList = questions
print("nil test: \(questionsCD.questions?.questionList ?? [])")
do {
try persistentContainer.viewContext.save()
} catch let error {
print("Failed to save selected category: \(error.localizedDescription)")
}
}
Core Data Get Function:
func getSelectedQuestion(questionID: String) -> [QuestionCD] {
let fetchRequest: NSFetchRequest<QuestionCD> = QuestionCD.fetchRequest()
let search = NSPredicate(format: "id == %#", questionID)
print("search: \(search)")
fetchRequest.predicate = search
fetchRequest.returnsObjectsAsFaults = false
print("request predicate: \(String(describing: fetchRequest.predicate))")
do {
return try persistentContainer.viewContext.fetch(fetchRequest)
} catch let error {
print("get hata: \(error.localizedDescription)")
return []
}
}
Console Output:
selectedQuestionCD [<QuestionCD: 0x2800e8e60> (entity: QuestionCD; id: 0x9d00d28ec7359eb0 <x-coredata://089E80AC-0E4F-4303-BF8F-47C31EC70ED4/QuestionCD/p2>; data: {
id = "agustos_test_1";
questions = nil;
title = "A\U011fustos Test 1";
})]
Core Data Entity:
Questions NSSecure Coding:
public class QuestionsNSSecureCoding: NSObject, NSSecureCoding {
public static var supportsSecureCoding: Bool = true
var questionList: [QuestionList]
required init(questions: [QuestionList]) {
self.questionList = questions
}
public func encode(with coder: NSCoder) {
coder.encode(questionList, forKey: "questionList")
}
required public init?(coder: NSCoder) {
questionList = coder.decodeObject(of: NSArray.self, forKey: "questionList") as? Array<QuestionList> ?? []
}
}
Questions Value Transformer:
#objc(QuestionsValueTransformer)
final class QuestionsValueTransformer: NSSecureUnarchiveFromDataTransformer {
static let name = NSValueTransformerName(rawValue: String(describing: QuestionsValueTransformer.self))
override static var allowedTopLevelClasses: [AnyClass] {
return [QuestionsNSSecureCoding.self]
}
public static func register() {
let transformer = QuestionsValueTransformer()
ValueTransformer.setValueTransformer(transformer, forName: name)
}
}
My Custom Model:
class QuestionContainer: Codable {
var questionCategories: [Question]
init(questionCategories: [Question]) {
self.questionCategories = questionCategories
}
}
class Question: Codable, Identifiable {
var title: String
var id: String
var questions: [QuestionList]
init(title: String, id: String, questions: [QuestionList]) {
self.title = title
self.id = id
self.questions = questions
}
}
class QuestionList: Codable, Identifiable {
var id: String
init(id: String) {
self.id = id
}
}
I think the problem is that questionCD.questions is nil, so the line
questionsCD.questions?.questionList = questions
does nothing. You need to create an instance of QuestionsNSSecureCoding with the correct questions array, and assign that to the questions property:
questionsCD.questions = QuestionsNSSecureCoding(questions: questions)

How to save and load array of objects - Swift 4

Here is my code from my app called Reminders:
Folder Class:
class Folder
{
var name: String
var labelName: String
var imageName : String
var colour : ColourTheme
var colourArray : Array<UIColor>
var maxNumOfPages : Int
var text : Array<String>
var touchID : Bool
var isNewFolder : Bool
init (name: String, labelName: String, imageName: String, colour: ColourTheme, maxNumOfPages: Int, text: Array<Any>, touchID: Bool, isNewFolder: Bool)
{
self.name = name
self.labelName = labelName
self.imageName = imageName
self.colour = colour
self.colourArray = []
self.maxNumOfPages = maxNumOfPages
self.text = text as! Array<String>
self.touchID = touchID
self.isNewFolder = isNewFolder
}
Main VC:
func resetData ()
{
folderArray.removeAll()
let folder1 = Folder.init(name: "reminders", labelName: "reminders", imageName: "reminders(bell)(notifications)", colour: .light, maxNumOfPages: 10, text: [""], touchID: false, isNewFolder: false)
folderArray.append(folder1)
}
func saveData()
{
let myData = NSKeyedArchiver.archivedData(withRootObject: folderArray)
UserDefaults.standard.set(myData, forKey: "folderArrayD")
print("place saved")
}
func loadData()
{
let foldersData = UserDefaults.standard.object(forKey: "folderArrayD") as? NSData
if let foldersData = foldersData
{
let folderArray = NSKeyedUnarchiver.unarchiveObject(with: foldersData as Data) as? [Folder]
if let folderArray = folderArray
{
print(folderArray)
}
}
I am trying to save and load my folder objects array at different various points in my program.
At the moment it is giving this error:
NSForwarding: warning: object 0x280e3c600 of class 'Reminder.Folder' does not implement methodSignatureForSelector: -- trouble ahead
Unrecognized selector -[Reminder.Folder replacementObjectForKeyedArchiver:]
I have looked everywhere to try fix this please could someone help, thank you!
Your Folder Model class need Inherits from NSObject and to adopt the protocol and its required methods for store data in UserDefaults.
like this:
class Folder: NSObject {
var name: String
var labelName: String
.....
init (name: String, labelName: String .....)
{
self.name = name
self.labelName = labelName
......
}
}
Your Folder class needs to be inherits from NSObject and NScoding and protocol required with encoder an Decoder
class Folder: NSObject, NSCoding {
var name: String
var labelName: String
.....
struct keys {
static let name = "name"
static let labelName = "labelName"
}
init (name: String, labelName: String .....)
{
self.name = name
self.labelName = labelName
......
}
required init(coder aDecoder: NSCoder) {
self.name = aDecoder.decodeObject(forKey: keys.name) as? String ?? ""
self. labelName = aDecoder.decodeObject(forKey: keys. labelName) as? String ?? ""
}
func encode(with aCoder: NSCoder) {
aCoder.encode(self.emailId, forKey: keys.name)
aCoder.encode(self.userId, forKey: keys.labelName)
}
}

Retrieving image from firebase? (swift)

So i have a firebase structure like the pic below
Now i want to retrieve that image file that i've uploaded. to decode the base64String and show it. Every user can make a post and the information that will be sended to firebase has a description etc. and also have an image. now i tried to retrieve it whit this codes but nothing did work.
var REF_LIST = Firebase(url: "\(URL_BASE)/listItems")
REF_LIST.observeEventType(FEventType.Value, withBlock: { snapshot in
let image = snapshot.value.objectForKey("images") as! String
but this already gave me a nil error on that line, so i couldn't even decode. i think i understand why it's giving me a nil error, there is no images in listItems on firebase, you first have the unique ID and then the specs with images in. now i don't now how i can retrieve that information from that unique ID?
UPDATE:
the tableViewController what will receive the data from firebase:
import UIKit
import FBSDKLoginKit
import Alamofire
import Firebase
class ListVC: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
var lists = [List]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
dispatch_async(backgroundQueue, {
self.initObservers()
})
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.tableView.reloadData()
}
func initObservers() {
LoadingOverlay.shared.showOverlay(self.view)
DataService.ds.REF_LISTS.observeEventType(.Value, withBlock: { snapshot in
print(snapshot.value)
self.lists = []
if let snapshots = snapshot.children.allObjects as? [FDataSnapshot] {
for snap in snapshots {
print("SNAP: \(snap)")
if let listDict = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key
let list = List(listKey: key, dictionary: listDict)
self.lists.insert(list, atIndex:0)
}
}
}
self.tableView.reloadData()
LoadingOverlay.shared.hideOverlayView()
})
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return lists.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCellWithIdentifier("ListCell") as? ListCell {
let list = self.lists[indexPath.row]
cell.request?.cancel()
cell.configureCell(list)
return cell
} else {
return ListCell()
}
}
}
the addController which post the data to firebase:
import UIKit
import Firebase
import Alamofire
import FBSDKCoreKit
class AddVC: UIViewController, UITextFieldDelegate, UITextViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var addTitle: UITextField!
#IBOutlet weak var addDescription: UITextView!
#IBOutlet weak var addLocation: UITextField!
#IBOutlet weak var placeholderLbl: UILabel!
#IBOutlet weak var freeSwitch: UISwitch!
#IBOutlet weak var tradeSwitch: UISwitch!
#IBOutlet weak var imageSelectorImg: UIImageView!
#IBOutlet weak var overlayView: UIView!
var currentUsername = ""
var imageSelected = false
var imagePicker: UIImagePickerController!
var base64String: NSString = ""
override func viewDidLoad() {
super.viewDidLoad()
addTitle.delegate = self
addDescription.delegate = self
addLocation.delegate = self
imagePicker = UIImagePickerController()
imagePicker.delegate = self
getCurrentUser()
hideKeyboardWhenTappedAround()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
addTitle.text = ""
addDescription.text = ""
addLocation.text = ""
freeSwitch.setOn(false, animated: false)
tradeSwitch.setOn(false, animated: false)
placeholderLbl.hidden = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getCurrentUser() {
DataService.ds.REF_USER_CURRENT.observeEventType(FEventType.Value, withBlock: { snapshot in
let currentUser = snapshot.value.objectForKey("username") as! String
print("Username: \(currentUser)")
self.currentUsername = currentUser }, withCancelBlock: { error in
print(error.description)
})
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
imagePicker.dismissViewControllerAnimated(true, completion: nil)
imageSelectorImg.image = image
dispatch_async(backgroundQueue, {
let uploadImage = image
let imageData = UIImageJPEGRepresentation(uploadImage, 0.5)
self.base64String = imageData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
})
imageSelected = true
}
#IBAction func selectImage(sender: UITapGestureRecognizer) {
presentViewController(imagePicker, animated: true, completion: nil)
}
func postToFirebase() {
// LoadingOverlay.shared.showOverlay(self.overlayView)
var post: Dictionary<String, AnyObject> = ["username": self.currentUsername, "description": self.addDescription.text!, "title": self.addTitle.text!, "location": self.addLocation.text!, "images": self.base64String]
if self.freeSwitch.on && self.tradeSwitch.on {
post["tradeOption"] = "Gratis/Te ruil"
} else if self.freeSwitch.on {
post["tradeOption"] = "Gratis"
} else if self.tradeSwitch.on {
post["tradeOption"] = "Te ruil"
}
let firebasePost = DataService.ds.REF_LISTS.childByAutoId()
firebasePost.setValue(post)
}
#IBAction func postListItem(sender: AnyObject) {
if let addTitle = addTitle.text where addTitle != "", let addDescription = addDescription.text where addDescription != "", let addLocation = addLocation.text where addLocation != "" {
dispatch_async(backgroundQueue, {
self.postToFirebase()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let listVC = storyboard.instantiateViewControllerWithIdentifier("TBC") as! UITabBarController
listVC.selectedIndex = 1
self.presentViewController(listVC, animated: false, completion: nil)
})
})
}
}
func textViewDidBeginEditing(textView: UITextView) {
placeholderLbl.hidden = true
}
func textViewDidEndEditing(textView: UITextView) {
if textView.text == "" {
placeholderLbl.hidden = false
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
and the swift file to configure the cell:
import UIKit
import Alamofire
import Firebase
class ListCell: UITableViewCell {
#IBOutlet weak var listImg: UIImageView!
#IBOutlet weak var listTitle: UILabel!
#IBOutlet weak var listTradeOption: UILabel!
#IBOutlet weak var listLocation: UILabel!
#IBOutlet weak var headImg: UIImageView!
var list: List!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func retrieveImages() {
DataService.ds.REF_LISTS.observeEventType(FEventType.Value, withBlock: { snapshot in
if let snapshots = snapshot.children.allObjects as? [FDataSnapshot] {
for snap in snapshots {
let image = snap.value.objectForKey("images") as! String
let decodedData = NSData(base64EncodedString: image, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
let decodedImage = UIImage(data: decodedData!)
self.headImg.image = decodedImage
}
}
})
}
func configureCell(list: List) {
self.list = list
self.listTitle.text = list.listTitle
self.listTradeOption.text = list.listTradeOption
self.listLocation.text = list.listLocation
retrieveImages()
}
}
also the list Model file:
import Foundation
import Firebase
class List {
private var _listTitle: String!
private var _listDescription: String!
private var _listTradeOption: String!
private var _listLocation: String!
private var _listImageURL: String?
private var _listKey: String!
private var _listRef: Firebase!
var listTitle: String? {
return _listTitle
}
var listDescription: String? {
return _listDescription
}
var listTradeOption: String? {
return _listTradeOption
}
var listLocation: String? {
return _listLocation
}
var listKey: String {
return _listKey
}
var listImageURL: String? {
return _listImageURL
}
init(title: String, description: String, tradeOption: String, location: String, listImageURL: String?) {
self._listTitle = title
self._listDescription = description
self._listTradeOption = tradeOption
self._listLocation = location
self._listImageURL = listImageURL
}
init(listKey: String, dictionary: Dictionary<String, AnyObject>) {
self._listKey = listKey
if let title = dictionary ["title"] as? String {
self._listTitle = title
}
if let desc = dictionary ["description"] as? String {
self._listDescription = desc
}
if let trade = dictionary ["tradeOption"] as? String {
self._listTradeOption = trade
}
if let loc = dictionary ["location"] as? String {
self._listLocation = loc
}
if let imgUrl = dictionary["images"] as? String {
self._listImageURL = imgUrl
}
self._listRef = DataService.ds.REF_LISTS.childByAppendingPath(self._listKey)
}
}
i've got also a DataServicefile, where i create a user by unique ID with this code:
var REF_USER_CURRENT: Firebase {
let uid = NSUserDefaults.standardUserDefaults().valueForKey(KEY_UID) as! String
let user = Firebase(url: "\(REF_BASE)").childByAppendingPath("users").childByAppendingPath(uid)
return user!
}
func createFirebaseUser(uid: String, user: Dictionary<String, String>) {
REF_USERS.childByAppendingPath(uid).setValue(user)
}
i know it's a lot but maybe the best way to help :)
Try editing this in List Cell
var imageURL = String()
func retrieveImages() {
let decodedData = NSData(base64EncodedString: imageURL, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
let decodedImage = UIImage(data: decodedData!)
self.headImg.image = decodedImage
}
func configureCell(list: List) {
self.list = list
self.listTitle.text = list.listTitle
self.listTradeOption.text = list.listTradeOption
self.listLocation.text = list.listLocation
self.imageURL = list.listImageURL //you already had the image url for that specific cell
retrieveImages()
}
Storing and accessing images using base64String in firebase is not an
efficient way, instead of that we can use FirebaseStorage (Google cloud storage
bucket) for uploading images to Firebase and it will provide us
download URL for a particular image. We can store that URL into our database simply in a string format and access it whenever we
required and then download the corresponding image from that URL by
using SDWebImage.
Refer below link for integrating FirebaseStorage into your project: https://firebase.google.com/docs/storage/ios/upload-files

swift use class instances to implement variable

My aim is to implement first a viewtable with json data in a view controller.
Then in another viewcontroller i want to choose some record from table to view.
First my class Route is above
class Route {
var id: Int?
var travelTimeSeconds: Int?
var condition:String?
var lastUpdate:String?
var title:String?
var backup = [Route]()
init(json: NSDictionary) {
self.id = json["id"] as? Int
self.travelTimeSeconds = json["travelTimeSeconds"] as? Int
self.condition = json["condition"] as? String
self.lastUpdate = json["lastUpdate"] as? String
self.title = json["title"] as? String
}
init(){}
func findRoutes(predferedroute:String)->[Route] {
let jsonurl = NSURL(string: predferedroute)!
let task = NSURLSession.sharedSession().dataTaskWithURL(jsonurl) { (data,response, error) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if let urlcontent = data {
do{
let jsonresult = try NSJSONSerialization.JSONObjectWithData(urlcontent, options: NSJSONReadingOptions.MutableContainers)
if let routeArray = jsonresult["result"] as? [NSDictionary] {
for item in routeArray {
self.backup.append(Route(json: item))
}//end for
}//end if
}//end do
catch {
print("Serialization error")
}//end catch
}//end if
})//end dispatch
}//end task
task.resume()
return self.backup
}//end findRoutes
}
in the first view cotroller i write the following code
class MenuPageViewController: UIViewController{
var routes = [Route]()
var implementroutes = Route()
var allroutes:String = "http://quickweb.gr/itsweb/webservices/json?op=GetAll"
var activeRoutes:String = "http://quickweb.gr/itsweb/webservices/json?op=GetActive"
override func viewDidLoad() {
super.viewDidLoad()
NSUserDefaults.standardUserDefaults().setObject("palios55", forKey: "StartUp")
let nickname1 = NSUserDefaults.standardUserDefaults().objectForKey("StartUp")!
print(nickname1)
routes = implementroutes.findRoutes(allroutes)
routes = implementroutes.backup
}//end viewload
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
the other delegates for table view works
but still remain nil the routes for both of two codes:
routes = implementroutes.findRoutes(allroutes)
routes = implementroutes.backup
Does i miss something with viewcontrollers and classes?
if i use the same code directly in tableview it works.