Post not yet marked as solved
I've been able to solve the issue of caching images to improve scroll performance in my app. However nil is found when it tries to add it to cache. Also how can I add a placeholder image for images that failed to load or aren't available ? https://github.com/lexypaul13/Image-Search
extension UIImageView {
func downloadImage(from imgURL: String) -> URLSessionDataTask? {
guard let url = URL(string: imgURL) else { return nil }
// set initial image to nil so it doesn't use the image from a reused cell
image = nil
// check if the image is already in the cache
if let imageToCache = imageCache.object(forKey: imgURL as NSString) {
self.image = imageToCache
return nil
}
// download the image asynchronously
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if let err = error {
print(err)
return
}
DispatchQueue.main.async {
// create UIImage
let imageToCache = UIImage(data: data!)
// add image to cache
imageCache.setObject(imageToCache!, forKey: imgURL as NSString)
self.image = imageToCache
}
}
task.resume()
return task
}
}
Post not yet marked as solved
The search bar in the weekly view controller in my app isn't working. It fails to show the corresponding cell from the text in the search bar. Project: link:https://github.com/lexypaul13/Trending-Tv-Shows
isSearching = False
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
var activeArray: Show
if isSearching {
activeArray = shows[indexPath.row]
} else {
activeArray = filteredShows[indexPath.row]
}
let detailsVC = Details_ViewController(showID:show_ID)
detailsVC.showID = activeArray.id ?? 0
let navController = UINavigationController(rootViewController: detailsVC)
present(navController, animated: true)
}
func updateUI(_ shows:[Show]){
if self.shows.isEmpty{
let alert = UIAlertController(title: "Tv Show Doesnt Exist", message: nil,preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
self.updateData(shows: self.shows)
}
func updateData(shows:[Show]){ //shows follwers
var snapshot = NSDiffableDataSourceSnapshot<Section,Show>()
snapshot.appendSections([.main])
snapshot.appendItems(shows)
DispatchQueue.main.async {
self.dataSource.apply(snapshot,animatingDifferences: true)
}
}
func updateSearchResults(for searchController: UISearchController) {
if searchController.searchBar.text != ""{
filteredShows = shows.filter({$0.unwrappedName.lowercased().contains((searchController.searchBar.text ?? "").lowercased())})
updateData(shows: filteredShows)
}
else {
updateData(shows: shows)
}
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
isSearching = false
updateData(shows: filteredShows)
}
Post not yet marked as solved
My app connects to a web service to display JSON data in a table view. Right now, its memory usage is terrible and needs improvement; while performing a memory leak check on instrument, it shows issues related to "WKWebsiteDataStore." What does this mean, and how do I resolve it? The code below shows a web view from a selected table view cell.
Project link https://github.com/lexypaul13/Covid-News
import UIKit
import WebKit
class ArticleViewController: UIViewController {
&#9;
&#9;@IBOutlet weak var articlePage: WKWebView!
&#9;var website: ArticlesData?
&#9;
&#9;override func viewDidLoad() {
&#9;&#9;super.viewDidLoad()
&#9;&#9;
&#9;&#9;if let url = URL(string: website?.urlWebsite ?? "" ) {
&#9;&#9;&#9;let request = URLRequest(url: url)
&#9;&#9;&#9;articlePage.load(request)
&#9;&#9;&#9;// Do any additional setup after loading the view.
&#9;&#9;}
&#9;}
&#9;
}
Post not yet marked as solved
How can I sort by date, the parsed json in this function ?
func parseData(data: Data) -> [ArticlesData]? {
do {
let jsonResult = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
let jsonArticles = jsonResult?["articles"] as? [AnyObject] ?? [] // gets first head of json file and converts it to dictionary
for jsonArticle in jsonArticles { // captures data and stores it in the model object
let article = ArticlesData()
article.author = jsonArticle["author"] as? String
article.myDescription = jsonArticle["description"] as? String
article.publishedAt = jsonArticle["publishedAt"] as? String
article.urlImage = jsonArticle["urlToImage"] as? String
article.urlWebsite = jsonArticle["url"] as? String
articles?.append(article) //put article data in the array
}
let nc = NotificationCenter.default
nc.post(name: Notification.Name("didFinishParsing"), object: nil)
} catch {
print("\(error)")
}
return articles ?? []
}
Post not yet marked as solved
I am trying to save JSON data received from a web service into my core data model. This works by swiping left from a table view cell to save. When I try to look at the saved data from a database, nothing shows. Can someone please have a look? The code below handles persistence.
https://github.com/lexypaul13/Covid-News
Error Message: [] nwprotocolgetquicimageblockinvoke dlopen libquic failed
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let save = UIContextualAction(style: .normal, title: "Save") { (action, view, completionHandler) in
completionHandler(true)
CoreDataManger.sharedInstance.createData()
}
save.backgroundColor = .systemBlue
let swipe = UISwipeActionsConfiguration(actions: [save])
return swipe
}
_
class CoreDataManger: NSObject {
static let sharedInstance = CoreDataManger()
private override init() {}
var newsCoreData: [News] = []
var article = ArticlesData()
// MARK: - Core Data Saving support
func createData(){
//As we know that container is set up in the AppDelegates so we need to refer that container.
DispatchQueue.main.async(execute: { [self] in
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
//We need to create a context from this container
let managedContext = appDelegate.persistentContainer.viewContext
//Now let’s create an entity and new user records.
let newsEntity = NSEntityDescription.entity(forEntityName: "News", in: managedContext)!
for article in self.newsCoreData{
let news = NSManagedObject(entity: newsEntity, insertInto: managedContext)
news.setValue("\(article.author ?? "")", forKeyPath: "author")
news.setValue("\(article.myDescription ?? "")", forKeyPath: "myDescription")
news.setValue("\(article.publishedAt ?? "")", forKeyPath: "publishAt")
news.setValue("\(article.title ?? "")", forKeyPath: "title")
news.setValue("\(article.urlImage ?? "")", forKeyPath: "urlImage")
news.setValue("\(article.urlWebsite ?? "")", forKeyPath: "urlWebsite")
}
//Now we have set all the values. The next step is to save them inside the Core Data
do {
try managedContext.save()
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
print(FileManager.default.urls(for: .documentDirectory, in: .userDomainMask))
}
)}
}
I am trying to download an image into a table view cell. I have a class the parses data and performs a network request called Article Manger. I also extended the UIImage View to download the image; however, I keep getting an error that says "Variable 'image' used before being initialized." How can I fix this?
https://github.com/lexypaul13/Covid-News
extension UIImageView {
func downloadImage( url: String){
let news = ArticleManger()
news.performRequest(urlString: url)
DispatchQueue.main.async {
var image:Data
self.image = UIImage(data: image)
}
}
The search bar in my app isn't working. Ive narrowed down the problem to the method cellforRowAt. It's not able to show the search result when word are typed. Can someone please assist me ? Project Link: https://github.com/lexypaul13/Covid-News.git
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //determines what data source should be used when user types
if isFiltering{
return filteredArticles?.count ?? 0
}
return articles?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! NewsTableViewCell
let news: Articles
filteredArticles = articles
if isFiltering{
news = filteredArticles![indexPath.row]
}
else{
news = articles![indexPath.row]
}
cell.authorName.text = filteredArticles?[indexPath.row].author
cell.headLine.text = filteredArticles?[indexPath.row].title
cell.newsImage.downloadImage(from:(self.filteredArticles?[indexPath.item].urlImage ?? "nill"))
cell.timePublication.text = filteredArticles?[indexPath.row].publishedAt
if let dateString = filteredArticles?[indexPath.row].publishedAt,
let date = indDateFormatter.date(from: dateString){
let formattedString = outDateFormtter.string(from: date)
cell.timePublication.text = formattedString
} else {
cell.timePublication.text = "----------"
}
return cell
}
func updateSearchResults(for searchController: UISearchController) {
let searchBar = searchController.searchBar
filterContentForSearchText(searchBar.text!, articles!)
}
func filterContentForSearchText(_ searchText:String ,_ category: [Articles]){
filteredArticles = articles?.filter({ (article:Articles) -> Bool in
return article.description.lowercased().contains(searchText.lowercased())
})
table_view.reloadData()
}
Post not yet marked as solved
I want to implement a search bar in my app, However I can't access the methods to manipulate strings such filter, lowercase, contain etc. Can anyone provide a suggestion on how can I solve this issue ? I am a beginner.
Here's my model
class Articles: NSObject{
var author: String?
var title: String?
var publishedAt: String?
var urlImage: String?
var urlWebsite : String?
}
class LatestNewsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let newsData = Articles() //Model object
let urlRequest = "https://newsapi.org/v2/everything?q=coronavirus&apiKey=" //Website API
var urlSelected = ""
var articles: [Articles]? = [] // holds array of Articles data
var indexOfPageToRequest = 1
@IBOutlet weak var tableview: UITableView!
func parseData(data:Data)-> [Articles] {
var articles: [Articles]? = [] // holds parsed data
do {
let jsonResult = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
let jsonArticles = jsonResult?["articles"] as? [AnyObject] ?? [] // gets first head of json file and converts it to dictionary
for jsonArticle in jsonArticles{ // captures data and stores it in the model object
let article = Articles()
article.author = jsonArticle["author"] as? String
article.title = jsonArticle["description"] as? String
article.publishedAt = jsonArticle["publishedAt"] as? String
article.urlImage = jsonArticle["urlToImage"] as? String
article.urlWebsite = jsonArticle["url"] as? String
articles?.append(article) //put article data in the array
}
print(jsonArticles)
DispatchQueue.main.async {
if(articles!.count > 0)
{
self.tableview.reloadData()
}
}
} catch {
print("Nothing my guy\(error)")
}
return articles ?? [] // returns an array of articles
}
func tableView( tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return articles?.count ?? 0
}
func tableView( tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! NewsTableViewCell
cell.authorName.text = articles?[indexPath.row].author
cell.headLine.text = articles?[indexPath.row].title
cell.newsImage.downloadImage(from:(self.articles?[indexPath.item].urlImage ?? "nill"))
cell.timePublication.text = articles?[indexPath.row].publishedAt
return cell
}
func searchBar(_ searchBar: UISearchBar,textDidChange searchText: String){
filteredData = []
}
How do I make a text label in a table view cell show "dd-MM-yyyy " instead of ISO 8601 retrieved from a web service ?
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! NewsTableViewCell
cell.authorName.text = articles?[indexPath.row].author
cell.headLine.text = articles?[indexPath.row].title
cell.newsImage.downloadImage(from:(self.articles?[indexPath.item].urlImage ?? "nill"))
cell.timePublication.text = articles?[indexPath.row].publishedAt
return cell
}
Post not yet marked as solved
How do I show more table cells from the newsapi.org ; right now it only shows 19. How do I increase the number to show more when the user scrolls down ? Please look at the LatestNewsView Controller
https://github.com/lexypaul13/Covid-News
My table view cells aren't showing the date of json files collected from NewsApi.com. Can someone pls help ? Link to project below Link to project below. In in the LatestNewsViewController
https://github.com/lexypaul13/Covid-News
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! NewsTableViewCell
cell.authorName.text = articles?[indexPath.row].author
cell.headLine.text = articles?[indexPath.row].title
cell.newsImage.downloadImage(from:(self.articles?[indexPath.item].urlImage ?? "nill"))
if let date = articles?[indexPath.row].publishedAt{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
guard let time = dateFormatter.date(from: date) else { return cell }
let formattedString = dateFormatter.string(from:time)
cell.timePublication.text = formattedString
}
return cell
}