Incorrect argument label in call (have 'named:', expected 'systemName:') - ios

I want to show the contents of the collection view through search. However, there are many errors while binding collection views. I think the model code got weird first, where is it weird? How can we fix this error?
output.loadData.map(CollectionOfOne.init).bind(to: collectionView.rx.items) { (row,collectionView, element) -> UICollectionViewCell in
let indexPath = IndexPath(index: 1)
guard let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "friendCell", for: indexPath) as? FriendCell else {
return FriendCell()
}
cell.profileImage?.image = UIImage(systemName: element.image)
cell.nickNameLbl?.text = element.nickname
cell.listenBtn?.rx.tap.subscribe(onNext: {[unowned self] in
selectIndexPath.accept(row)
}).disposed(by: cell.disposeBag)
return cell
}
output.searchNameResult.map(CollectionOfOne.init).bind(to: collectionView.rx.items) { collectionView, index, element -> UICollectionViewCell in
let indexPath = IndexPath(index: 0)
guard let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "freindCell", for: indexPath) as? FriendCell else {
return FriendCell()
}
// cell.profileImage?.image = UIImage(systemName: (element as AnyObject).image)
cell.profileImage?.image = UIImage(named: element.img)
cell.nickNameLbl?.text = (element.nickname)
return cell
}
This is viewcontroller code
struct input {
let loadData: Signal<Void>
let searchName: Driver<Void>
let searchHashTag: Driver<Void>
}
struct output {
let loadData: BehaviorRelay<[User]>
let searchNameResult: PublishRelay<users>
}
func transform(_ input: input) -> output {
let api = SearchAPI()
let loadData = BehaviorRelay<[User]>(value: [])
let searchName = PublishRelay<users>()
input.loadData.asObservable().subscribe(onNext: { [weak self] in
guard let self = self else { return }
api.getFriend().subscribe(onNext: { (response, statuscode) in
switch statuscode {
case .ok:
// loadData.accept(response!, User)
result.onCompleted()
default:
result.onNext("default")
}
}).disposed(by: self.disposeBag)
}).disposed(by: disposeBag)
input.searchName.asObservable().withLatestFrom(input.name).subscribe(onNext: {[weak self] nickname in
guard let self = self else { return }
api.getUserList(nickname).subscribe(onNext: { (response,statuscode) in
switch statuscode {
case .ok:
result.onCompleted()
case .noHere:
result.onNext("no user")
default:
result.onNext("default")
}
}).disposed(by: self.disposeBag)
}).disposed(by: disposeBag)
And this is my viewmodel.
What is the problem?

You are getting the error: Incorrect argument label in call (have 'named:', expected 'systemName:') because of this other error: Value of type 'users' has no member 'img'.
I expect that you don't really want to display a single cell but the code is so muddled in general that it's hard to make out exactly what you are trying to do. I suggest you find yourself a tutor who can teach you about types, or possibly use the Swift Playgrounds app to learn the basics of how to code before you try to make a real program.

Related

do(onNext:) called twice when table view row is selected

I'm facing a problem when selecting the table view row on RxSwift. For details, the code on the do(onNext:) function is called twice, thus lead to the navigation pushed twice too. Here is my code in the viewModel, please help me resolve it. Thanks so much.
struct Input {
let loadTrigger: Driver<String>
let searchTrigger: Driver<String>
let selectMealTrigger: Driver<IndexPath>
}
struct Output {
let mealList: Driver<[Meal]>
let selectedMeal: Driver<Meal>
}
func transform(_ input: HomeViewModel.Input) -> HomeViewModel.Output {
let popularMeals = input.loadTrigger
.flatMap { _ in
return self.useCase.getMealList()
.asDriver(onErrorJustReturn: [])
}
let mealSearchList = input.searchTrigger
.flatMap { text in
return self.useCase.getMealSearchList(mealName: text)
.asDriver(onErrorJustReturn: [])
}
let mealList = Observable.of(mealSearchList.asObservable(), popularMeals.asObservable()).merge().asDriver(onErrorJustReturn: [])
let selectedMeal = input.selectMealTrigger
.withLatestFrom(mealList) { $1[$0.row] }
.do(onNext: { meal in
self.navigator.toMealDetail(meal: meal)
})
return Output(mealList: mealList, selectedMeal: selectedMeal)
}
Edit: Here's the implemetation on the ViewController:
func bindViewModel() {
self.tableView.delegate = nil
self.tableView.dataSource = nil
let emptyTrigger = searchBar
.rx.text.orEmpty
.filter { $0.isEmpty }
.throttle(0.1, scheduler: MainScheduler.instance)
.asDriver(onErrorJustReturn: "")
let loadMealTrigger = Observable
.of(emptyTrigger.asObservable(), Observable.just(("")))
.merge()
.asDriver(onErrorJustReturn: "")
let searchTrigger = searchBar.rx.text.orEmpty.asDriver()
.distinctUntilChanged()
.filter {!$0.isEmpty }
.throttle(0.1)
let selectMealTrigger = tableView.rx.itemSelected.asDriver()
let input = HomeViewModel.Input(
loadTrigger: loadMealTrigger,
searchTrigger: searchTrigger,
selectMealTrigger: selectMealTrigger
)
let output = viewModel.transform(input)
output.mealList
.drive(tableView.rx.items(cellIdentifier: MealCell.cellIdentifier)) { index, meal, cell in
let mealCell = cell as! MealCell
mealCell.meal = meal
}
.disposed(by: bag)
output.selectedMeal
.drive()
.disposed(by: bag)
}
Firstly, is this RxSwift?
If so, the .do(onNext:) operator provides side effects when you receive a new event via a subscription; Therefore, two "reactions" will happen when a table row is tapped: 1. subscription method and 2. .do(onNext:) event. Unfortunately, I do not have any further insight into your code, so there may be other stuff creating that error aswell.
Good luck!

Tableview not receiving signals from Driver

I have the following MVVM-C + RxSwift code.
The problem is that the TableView is not receiving any signals. When I
debug the results I can see that the API call is returning what it should, the objects array is populated with objects but the tableview does not show any results. Here is the console output:
2018-11-13 16:12:08.107: searchText -> Event next(qwerty)
Search something: qwerty
2018-11-13 16:12:08.324: viewModel.data -> Event next([])
Could it be the tableview itself? Maybe wrong custom cell setup?
ViewController.swift:
tableView = UITableView(frame: self.view.frame)
tableView.delegate = nil
tableView.dataSource = nil
tableView.register(SearchResultCell.self, forCellReuseIdentifier: "SearchResultCell")
viewModel.data
.debug("viewModel.data", trimOutput: false)
.drive(tableView.rx.items(cellIdentifier: "SearchResultCell")) { row, object, cell in
cell.name.text = object.name
cell.something.text = object.something
}
.disposed(by: disposeBag)
ViewModel.swift:
let disposeBag = DisposeBag()
var searchText = BehaviorRelay(value: "something to search for")
lazy var data: Driver<[Object]> = {
return self.searchText.asObservable()
.debug("searchText", trimOutput: false)
.throttle(0.3, scheduler: MainScheduler.instance)
.distinctUntilChanged()
.flatMapLatest(searchSomething)
.asDriver(onErrorJustReturn: [])
}()
func searchSomething(query: String) -> Observable<[Object]> {
print("Search something: \(query)")
let provider = MoyaProvider<APIService>()
var objects = [Object]()
provider.rx.request(.search(query: query)).subscribe { event in
switch event {
case let .success(response):
do {
let responseJSON: NSDictionary = try (response.mapJSON() as? NSDictionary)!
objects = self.parse(json: responseJSON["results"] as Any)
} catch(let error) {
print(error)
}
break
case let .error(error):
print(error)
break
}
}
.disposed(by: disposeBag)
let result: Observable<[Object]> = Observable.from(optional: objects)
return result
}
When using flatMap, you do not want to create nested subscriptions. You will create an Observable that returns the expected result, and flatMap will take care of subscribing to it. In the current state of things, searchSomething will always return an empty array, as Observable.from(optional: objects) will be called before the request has a chance to complete.
Since version 10.0 of Moya, provider will cancel the requests it created when deallocated. Here, it will be deallocated when execution exits searchSomething, hence the network request won't have time to finish. Moving provider's declaration to the view model's level solves this issue.
Here's searchSomething(query: String) -> Observable<[Object]> rewritten.
let provider = MoyaProvider<APIService>()
func searchSomething(query: String) -> Observable<[Object]> {
print("Search something: \(query)")
return provider.rx.request(.search(query: query)).map { (response) -> [Object] in
let responseJSON: NSDictionary = try (response.mapJSON() as? NSDictionary)!
return self.parse(json: responseJSON["results"] as Any)
}
}
Instead of doing the transformation in subscribe, it's done in map, which will be called for every next event, being passed the value associated with the event.

QueryEndingAtValue function does not work correctly in Swift firebase

I have been implementing code that is to enable paging scroll to fetch data by a certain amount of data from firebase database.
Firstly, then error says
Terminating app due to uncaught exception 'InvalidQueryParameter',
reason: 'Can't use queryEndingAtValue: with other types than string in
combination with queryOrderedByKey'
The below here is the actual code that produced the above error
static func fetchPostsWith(last_key: String?, completion: #escaping (([PostModel]?) -> Void)) {
var posts = [PostModel]()
let count = 2
let ref = Database.database().reference().child(PATH.all_posts)
let this_key = UInt(count + 1)
let that_key = UInt(count)
let this = ref.queryOrderedByKey().queryEnding(atValue: last_key).queryLimited(toLast: this_key)
let that = ref.queryOrderedByKey().queryLimited(toLast: that_key)
let query = (last_key != nil) ? this : that
query.observeSingleEvent(of: .value) { (snapshot) in
if snapshot.exists() {
for snap in snapshot.children {
if let d = snap as? DataSnapshot {
let post = PostModel(snapshot: d)
print(post.key ?? "")
posts.append(post)
}
}
posts.sort { $0.date! > $1.date! }
posts = Array(posts.dropFirst())
completion(posts)
} else {
completion(nil)
}
}
}
What it tries to do is to fetch a path where all posts are stored by auto id. But the error keeps coming out so I do not know what is wrong. Do you have any idea?
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
// index is the last and last fetched then
print(self.feeds.count - 1 == indexPath.row, "index ", self.hasFetchedLastPage, "has fetched last")
if self.feeds.count - 1 == indexPath.row {
let lastKey = self.feeds[indexPath.row].key
if lastKey != self.previousKey {
self.getFeeds(lastKey: lastKey)
} else {
self.previousKey = lastKey ?? ""
}
}
print("Cell Display Number", indexPath.row)
}
func getFeeds(lastKey: String?) {
print(self.isFetching, "is fetching")
guard !self.isFetching else {
self.previousKey = ""
return
}
self.isFetching = true
print(self.isFetching, "is fetching")
FirebaseModel.fetchPostsWith(last_key: lastKey) { ( d ) in
self.isFetching = false
if let data = d {
if self.feeds.isEmpty { //It'd be, when it's the first time.
self.feeds.append(contentsOf: data)
self.tableView.reloadData()
print("Initial Load", lastKey ?? "no key")
} else {
self.hasFetchedLastPage = self.feeds.count < 2
self.feeds.append(contentsOf: data)
self.tableView.reloadData()
print("Reloaded", lastKey ?? "no key")
}
}
}
}
I want to implement a paging enabled tableView. If you can help this code to be working, it is very appreciated.
You're converting your last_key to a number, while keys are always strings. The error message tells you that the two types are not compatible. This means you must convert your number back to a string in your code, before passing it to the query:
let this = ref.queryOrderedByKey().queryEnding(atValue: last_key).queryLimited(toLast: String(this_key))
let that = ref.queryOrderedByKey().queryLimited(toLast: String(that_key))

Issue trying to complete Firebase Storage download before showing tableview

I have a table view where depending on the cell class it will download an image from Firebase. I've noticed when using the app that cells with the same cell identifier will show the previous downloaded image before showing the new one. This is what I have before changing it.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableData[indexPath.row]["Image"] != nil {
let cell = tableView.dequeueReusableCell(withIdentifier: "imageNotesData", for: indexPath) as! ImageNotesCell
cell.notes.delegate = self
cell.notes.tag = indexPath.row
cell.notes.text = tableData[indexPath.row]["Notes"] as! String
guard let imageFirebasePath = tableData[indexPath.row]["Image"] else {
return cell }
let pathReference = Storage.storage().reference(withPath: imageFirebasePath as! String)
pathReference.getData(maxSize: 1 * 1614 * 1614) { data, error in
if let error = error {
print(error)
} else {
let image = UIImage(data: data!)
cell.storedImage.image = image
}
}
return cell
}
else {
let cell = tableView.dequeueReusableCell(withIdentifier: "notesData", for: indexPath) as! NotesCell
//let noteString = tableData[indexPath.row]["Notes"] as! String
cell.notes.text = tableData[indexPath.row]["Notes"] as! String
cell.notes.delegate = self
cell.notes.tag = indexPath.row
return cell
}
}
Knowing that this is not a good user experience and that it looks clunky, I tried to move the pathReference.getData to where I setup the data but the view appears before my images finish downloading. I have tried to use a completion handler but I'm still having issues.
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
getSectionData(userID: userID, city: selectedCity, completion: {(sectionString) in
self.setupTableCellView(userID: userID, city: selectedCity, section: sectionString) { (tableData) in
DispatchQueue.main.async(execute: {
self.cityName?.text = selectedCity
self.changeSections.setTitle(sectionString, for: .normal)
self.currentSectionString = sectionString
self.setupTableData(tableDataHolder: tableData)
})
}
})
}
func setupTableCellView(userID: String, city: String, section: String, completion: #escaping ([[String:Any]]) -> () ) {
let databaseRef = Database.database().reference().child("Users").child(userID).child("Cities").child(city).child(section)
var indexData = [String:Any]()
var indexDataArray = [[String:Any]]()
databaseRef.observeSingleEvent(of: .value, with: { (snapshot) in
for dataSet in snapshot.children {
let snap = dataSet as! DataSnapshot
//let k = snap.key
let v = snap.value
indexData = [:]
for (key, value) in v as! [String: Any] {
//indexData[key] = value
if key == "Image" {
//let pathReference = Storage.storage().reference(withPath: value as! String)
print("before getImageData call")
self.getImageData(pathRef: value as! String, completion: {(someData) in
print("before assigning indexData[key]")
indexData[key] = someData
print("after assigning indexData[key]")
})
} else {
indexData[key] = value
}
}
indexDataArray.append(indexData)
}
completion(indexDataArray)
})
}
func getImageData(pathRef: String, completion: #escaping(UIImage) -> ()) {
let pathReference = Storage.storage().reference(withPath: pathRef as! String)
pathReference.getData(maxSize: 1 * 1614 * 1614, completion: { (data, error) in
if let error = error {
print(error)
} else {
let image = UIImage(data:data!)
print("called before completion handler w/ image")
completion(image!)
}
})
}
I don't know if I am approaching this the right way but I think I am. I'm also guessing that the getData call is async and that is why it will always download after showing the table view.
You can't do this.
Make the request from Firebase.
Over time, you will get many replies - all the information and all the changing information.
When each new item arrives - and don't forget it may be either an addition or deletion - alter your table so that it displays all the current items.
That's OCC!
OCC is "occasionally connected computing". A similar phrase is "offline first computing". So, whenever you use any major service you use every day like Facebook, Snapchat, etc that is "OCC": everything stays in sync properly whether you do or don't have bandwidth. You know? The current major paradigm of device-cloud computing.
Edit - See Fattie's comments about prepareForReuse()!
With reusable table cells, the cells will at first have the appearance they do by default / on the xib. Once they're "used", they have whatever data they were set to. This can result in some wonky behavior. I discovered an issue where in my "default" case from my data, I didn't do anything ecause it already matched the xib, but if the data's attributes were different, I updated the appearance. The result was that scrolling up and down really fast, some things that should have had the default appearance had the changed appearance.
One basic solution to just not show the previous image would be to show a place holder / empty image, then call your asynchronous fetch of the image. Not exactly what you want because the cell will still show up empty...
Make sure you have a local store for the images, otherwise you're going to be making a server request for images you already have as you scroll up and down!
I'd recommend in your viewDidLoad, call a method to fetch all of your images at once, then, once you have them all, in your success handler, call self.tableview.reloadData() to display it all.

If/Else based on existence of object in array?

I want to trigger an else statement if there is no object at the indexPath i look for in an array.
The array is
let exerciseSets = unsortedExerciseSets.sorted { ($0.setPosition < $1.setPosition) }
Then i use let cellsSet = exerciseSets[indexPath.row]
There is a chance, when a user is adding a new cell, that it wont already have an exerciseSet at the indexPath to populate it (adding a new set to an existing array of sets) and so I need to run an else statement to set up a blank cell rather than attempting to populate it and crashing my app.
However if i use if let then i get this error:
Initializer for conditional binding must have Optional type, not
'UserExerciseSet'
Here is the whole function for context if needed:
func configure(_ cell: NewExerciseTableViewCell, at indexPath: IndexPath) {
if self.userExercise != nil {
print("RESTORING CELLS FOR THE EXISTING EXERCISE")
let unsortedExerciseSets = self.userExercise?.exercisesets?.allObjects as! [UserExerciseSet]
let exerciseSets = unsortedExerciseSets.sorted { ($0.setPosition < $1.setPosition) }
if let cellsSet = exerciseSets[indexPath.row] { // this causes a creash when user adds new set to existing exercise as it cant populate, needs an else statement to add fresh cell
cell.setNumber.text = String(cellsSet.setPosition)
cell.repsPicker.selectRow(Int(cellsSet.setReps), inComponent: 0, animated: true)
let localeIdentifier = Locale(identifier: UserDefaults.standard.object(forKey: "locale") as! String)
let setWeight = cellsSet.setWeight as! Measurement<UnitMass>
let formatter = MassFormatter()
formatter.numberFormatter.locale = localeIdentifier
formatter.numberFormatter.maximumFractionDigits = 2
if localeIdentifier.usesMetricSystem {
let kgWeight = setWeight.converted(to: .kilograms)
let finalKgWeight = formatter.string(fromValue: kgWeight.value, unit: .kilogram)
let NumericKgResult = finalKgWeight.trimmingCharacters(in: CharacterSet(charactersIn: "0123456789.").inverted)
cell.userExerciseWeight.text = NumericKgResult
} else {
let lbsWeight = setWeight.converted(to: .pounds)
let finalLbWeight = formatter.string(fromValue: lbsWeight.value, unit: .pound)
let NumericLbResult = finalLbWeight.trimmingCharacters(in: CharacterSet(charactersIn: "0123456789.").inverted)
cell.userExerciseWeight.text = NumericLbResult
}
} else {
cell.setNumber.text = String((indexPath.row) + 1)
}
You could do something crazy like this:
if let cellSet = (indexPath.row < exerciseSets.count ? exerciseSets[indexPath.row] : nil) {
//
}
but it would be more straightforward to do:
if indexPath.row < exerciseSets.count {
let cellSet = exerciseSets[indexPath.row]
...
}
OK, so your problem is that you are trying to access a value in an array that may or may not be there.
If you just try to access the value based on indexPath you can crash because indexPath may refer to a value not there. On the other hand, the array does not return an optional so you can't use if let either.
I kind of like the idea of using an optional, so how about introducing a function that could return an optional to you if it was there.
Something like:
func excerciseSet(for indexPath: IndexPath, in collection: [UserExcerciseSet]) -> UserExcerciseSet? {
guard collection.count > indexPath.row else {
return nil
}
return collection[indexPath.row]
}
and then you can say:
if let cellsSet = exerciseSet[for: indexPath, in: excerciseSets] {
//It was there...showtime :)
} else {
cell.setNumber.text = String((indexPath.row) + 1)
}
Hope that helps you.
Just check the index against your array count:
if indexPath.item < exerciseSets.count {
// Cell exists
let cellsSet = exerciseSets[indexPath.row]
} else {
// cell doesn't exists. populate new one
}

Resources