Daily App part1

動機:製作一個每日都會出現不一樣的資訊APP,包含有新聞、天氣、地圖找餐廳以及登入

登入已經實現了,但其實還在思考這APP 會需要用到登入嗎?但沒關係就當作練習把它串再一起。

新聞API

寫一個 class

class GetArticles {
static let share = GetArticles()

func getArt(completion: @escaping(Result<[Articles], Error>) -> Void){
let urlString = "https://newsapi.org/v2/top-headlines?country=us&apiKey=ad5c5f7946134e9a98087eba7ccaf28a"

guard let url = URL(string: urlString) else {return}
URLSession.shared.dataTask(with: url) { data, response, error in
if let data = data{
do{
let articServer = try JSONDecoder().decode(News.self, from: data)
print(articServer.articles.count)
completion(.success(articServer.articles))
}catch{
completion(.failure(error))
print(error)
}

}
}.resume()
}
}

建立一個 TableView,把抓到的 API 資料放進 TableViewCell 裡面,點擊 TableView會轉到一個 SFSafariViewController

class NewsTableViewController: UITableViewController {

var articles = [Articles]()

override func viewDidLoad() {
super.viewDidLoad()

GetArticles.share.getArt { result in
switch result {
case .success(let art):
self.articles = art
DispatchQueue.main.async {
self.tableView.reloadData()
}
case .failure(let error):
print(error)
}

}
}

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return articles.count
}


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "\(NewsTableViewCell.self)", for: indexPath) as! NewsTableViewCell
let result = articles[indexPath.row]
cell.InnerLabel.text = result.title
cell.NewsImage.image = UIImage(systemName: "photo")
if let imageURL = result.urlToImage {
URLSession.shared.dataTask(with: imageURL) { data, response, error in
if let data = data, let image = UIImage(data: data) {
DispatchQueue.main.async {
cell.NewsImage.image = image
}
}
}.resume()
}

return cell
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let url = URL(string: articles[indexPath.row].url) else {return}
let vc = SFSafariViewController(url: url)
present(vc, animated: true)
}

作品:

--

--