Currently, I am applying custom class SAFavoriteBtn to UIButton.
I wrote the code to get the API when the button was pressed within that class, I assigned the parameters to get the API data to the variables of UIViewController, I want to use the variable in SAFavoriteBtn. In this case, how should pass the value?
And this pattern is using segue?
UIViewController
class StoreViewController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate, UICollectionViewDelegateFlowLayout,UITableViewDelegate, UITableViewDataSource {
var store_id = ""
var instaId = ""
var store = [Store]()
var photoPath = [Store.photos]()
var tag = [Store.tags]()
var selectedImage : UIImage?
let defaultValues = UserDefaults.standard
#IBOutlet weak var imageCollectionView: UICollectionView!
#IBOutlet weak var mainImage: UIImageView!
#IBOutlet weak var nameLabel: UILabel!
#IBOutlet weak var locationLabel: UILabel!
#IBOutlet weak var UIView: UIView!
#IBOutlet weak var tagCollectionView: UICollectionView!
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
//Collectiopn DetaSources
imageCollectionView.dataSource = self
imageCollectionView.delegate = self
tagCollectionView.dataSource = self
tagCollectionView.delegate = self
tableView.dataSource = self
tableView.delegate = self
//Navigation Color
self.navigationController!.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController!.navigationBar.shadowImage = UIImage()
navigationController!.navigationBar.topItem!.title = ""
navigationController!.navigationBar.tintColor = UIColor.white
//UIView Shadow
let shadowPath = UIBezierPath(rect: UIView.bounds)
UIView.layer.masksToBounds = false
UIView.layer.shadowColor = UIColor.black.cgColor
UIView.layer.shadowOffset = .zero
UIView.layer.shadowOpacity = 0.2
UIView.layer.shadowPath = shadowPath.cgPath
//Request API
let url = URL(string: "http://example.com/store/api?store_id=" + store_id)
let request = URLRequest(url: url!)
let session = URLSession.shared
let encoder: JSONEncoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
encoder.outputFormatting = .prettyPrinted
session.dataTask(with: request){(data, response, error)in if error == nil,
let data = data,
let response = response as? HTTPURLResponse{
let decoder: JSONDecoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
do {
let json = try decoder.decode(Store.self, from: data)
self.store = [json]
self.photoPath = json.photos
self.tag = json.tags
if let imageURL = URL(string: "http://example.com/photos/" + json.photos[0].path){
DispatchQueue.global().async {
let data = try? Data(contentsOf: imageURL)
if let data = data {
let image = UIImage(data: data)
DispatchQueue.main.async {
self.mainImage.image = image
}
}
}
}else if let imageURL = URL(string: "http://example.com/photos/" + json.photos[0].path.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!){
DispatchQueue.global().async {
let data = try? Data(contentsOf: imageURL)
if let data = data {
let image = UIImage(data: data)
DispatchQueue.main.async {
self.mainImage.image = image
}
}
}
}
DispatchQueue.main.async {
self.nameLabel.text = json.name
self.locationLabel.text = json.location
self.tableView.reloadData()
self.imageCollectionView.reloadData()
self.tagCollectionView.reloadData()
}
} catch {
print("error:", error.localizedDescription)
}
}
}.resume()
print(store)
//print(defaultValues.string(forKey: "id"))
// Image Collection view Layout
let itemSize = UIScreen.main.bounds.width/3.62 - 3.62
let layout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0)
layout.itemSize = CGSize(width: itemSize, height: itemSize)
layout.minimumInteritemSpacing = 1
layout.minimumLineSpacing = 1
imageCollectionView.collectionViewLayout = layout
// Tag Collection View
let tagLayout = UICollectionViewFlowLayout()
tagLayout.minimumLineSpacing = 1
tagLayout.minimumInteritemSpacing = 1
tagLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0)
tagLayout.itemSize = CGSize(width: 80, height: 24)
tagCollectionView.collectionViewLayout = tagLayout
//status bar color
self.setNeedsStatusBarAppearanceUpdate()
}
override var prefersStatusBarHidden: Bool {
return false
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return UIStatusBarStyle.lightContent
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// UI coner redius
let uiViewPath = UIBezierPath(roundedRect: UIView.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 8, height: 8))
let uiViewMask = CAShapeLayer()
uiViewMask.path = uiViewPath.cgPath
UIView.layer.mask = uiViewMask
navigationController!.navigationBar.topItem!.title = " "
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Collection
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == self.imageCollectionView{
let imageCell:UICollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell",for: indexPath)
let imageView = imageCell.contentView.viewWithTag(1) as! UIImageView
let textLabel = imageCell.contentView.viewWithTag(2) as! UILabel
let instaBtn = imageCell.contentView.viewWithTag(3) as! UIButton
instaBtn.tag = indexPath.row
if photoPath.count > indexPath.row{
if collectionView == self.imageCollectionView{
let url : String = "http://example.com/photos/" + photoPath[indexPath.row].path
let imageURL = URL(string: url)
print(url)
if imageURL != nil {
DispatchQueue.global().async {
let data = try? Data(contentsOf: imageURL!)
if let data = data {
let image = UIImage(data: data)
DispatchQueue.main.async {
imageCell.layer.masksToBounds = true;
imageCell.layer.cornerRadius = 3
imageView.image = image
textLabel.text = self.photoPath[indexPath.row].username
print(self.photoPath[indexPath.row].username)
}
}
}
}else{
let encodeURL : String = "http://example.com/photos/" + photoPath[indexPath.row].path
let url = URL(string: encodeURL.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!)
DispatchQueue.global().async {
let data = try? Data(contentsOf: url!)
if let data = data {
let image = UIImage(data: data)
DispatchQueue.main.async {
imageCell.layer.masksToBounds = true;
imageCell.layer.cornerRadius = 3
imageView.image = image
textLabel.text = self.photoPath[indexPath.row].username
print(self.photoPath[indexPath.row].username)
}
}
}
}
}
}
instaBtn.addTarget(self, action: #selector(self.instaBtnTapped), for: UIControlEvents.touchUpInside)
imageCell.addSubview(instaBtn)
return imageCell
//Tag collection view
}else if collectionView == self.tagCollectionView{
let tagCell:UICollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "TagCell",for: indexPath)
let tagLabel = tagCell.contentView.viewWithTag(2) as! UILabel
if tag.count > indexPath.row{
tagLabel.text = tag[indexPath.row].name
}
tagCell.layer.cornerRadius = 12
return tagCell
}else{
return UICollectionViewCell()
}
}
//tapped instaBtn jump insta user page function
#objc func instaBtnTapped(sender: UIButton){
instaId = photoPath[sender.tag].username
let url = URL(string: "https://www.instagram.com/"+instaId+"/")
UIApplication.shared.open(url!, options: [ : ], completionHandler: nil)
print (sender.tag)
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return photoPath.count > 0 ? 3 : 0
}
func tagcollectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return tag.count > 0 ? tag.count : 0
}
func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return store.count > 0 ? 1 : 0
case 1 :
return store.count > 0 ? 1 : 0
case 2 :
return store.count > 0 ? 1 : 0
default:
return 0
}
}
//Collection view tap
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if collectionView == self.imageCollectionView{
let url : String = "http://example.com/photos/" + photoPath[indexPath.row].path
let imageURL = URL(string: url)
print(url)
if imageURL != nil {
DispatchQueue.global().async {
let data = try? Data(contentsOf: imageURL!)
if let data = data {
let image = UIImage(data: data)
DispatchQueue.main.async {
self.mainImage.image = image
}
}
}
}else{
let encodeURL : String = "http://example.com/photos/" + photoPath[indexPath.row].path
let url = URL(string: encodeURL.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!)
DispatchQueue.global().async {
let data = try? Data(contentsOf: url!)
if let data = data {
let image = UIImage(data: data)
DispatchQueue.main.async {
self.mainImage.image = image
}
}
}
}
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
switch indexPath.section {
case 0 :
//Price Cell
guard let priceCell = tableView.dequeueReusableCell(withIdentifier: "priceCell", for: indexPath) as? priceTableViewCell else { return UITableViewCell()}
if let price:String = store[indexPath.row].price{
priceCell.priceLabel.text! = price
}else{
priceCell.priceLabel.text! = "-"
}
return priceCell
case 1 :
//timeCell
guard let timeCell = tableView.dequeueReusableCell(withIdentifier: "timeCell", for: indexPath) as? timeTableViewCell else{return UITableViewCell()}
if let time:String = store[indexPath.row].open_time{
timeCell.timeLabel.text! = time
}else{
timeCell.timeLabel.text! = "-"
}
return timeCell
case 2 :
//closedayCell
guard let closedayCell = tableView.dequeueReusableCell(withIdentifier: "closedayCell", for: indexPath) as? closedayTableViewCell else { return UITableViewCell() }
if let closeday:String = store[indexPath.row].closed_day{
closedayCell.closedayLabel.text! = closeday
}else{
closedayCell.closedayLabel.text! = "-"
}
return closedayCell
default :
print("Default Selected")
}
return cell
}
#IBAction func moreImageBtn(_ sender: Any) {
let store_id = self.store_id
self.performSegue(withIdentifier: "toStorePhotoViewController", sender: store_id)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toStorePhotoViewController"{
let storePhotoViewController = segue.destination as! StorePhotoViewController
storePhotoViewController.store_id = sender as! String
}
}
//This is SAFavoriteBtn
//Bookmark Button
#IBAction func bookmarkBtn(_ sender: SAFavoriteBtn) {
}
#IBAction func locationBtn(_ sender: Any) {
let lat = store[0].lat
let lng = store[0].lng
if UIApplication.shared.canOpenURL(URL(string:"comgooglemaps://")!){
let urlStr : String = "comgooglemaps://?daddr=\(lat),\(lng)&directionsmode=walking&zoom=14"
UIApplication.shared.open(URL(string:urlStr)!,options: [:], completionHandler: nil)
}else{
let daddr = String(format: "%f,%f", lat, lng)
let urlString = "http://maps.apple.com/?daddr=\(daddr)&dirflg=w"
let encodeUrl = urlString.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)!
let url = URL(string: encodeUrl)!
UIApplication.shared.open(url,options: [:], completionHandler: nil)
}
}
}
SAFavoriteBtn
import UIKit
class SAFavoriteBtn: UIButton {
var isOn = false
let defaultValues = UserDefaults.standard
//Want to use the variable of UIViewController with UIButton custom class in this part
var storeId = ""
override init(frame: CGRect) {
super.init(frame:frame)
initButton()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initButton()
}
func initButton() {
setImage(UIImage(named:"bookmark.png"), for: UIControlState.normal)
addTarget(self, action: #selector(SAFavoriteBtn.buttonPressed), for: .touchUpInside)
}
#objc func buttonPressed() {
activateBtn(bool: !isOn)
}
func activateBtn(bool : Bool){
isOn = bool
//UI
let image = bool ? "bookmark_after.png" : "bookmark.png"
setImage(UIImage(named: image), for: UIControlState.normal)
//API
bool ? favorite() : deleteFavorite()
}
func favorite(){
let user_id = defaultValues.string(forKey: "userId")
let url = URL(string: "http://example.com/api/store/favorite?")
var request = URLRequest(url: url!)
request.httpMethod = "POST"
let postParameters = "user_id=" + user_id! + "&store_id=" + storeId
request.httpBody = postParameters.data(using: .utf8)
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if error == nil, let data = data, let response = response as? HTTPURLResponse {
print("Content-Type: \(response.allHeaderFields["Content-Type"] ?? "")")
print("statusCode: \(response.statusCode)")
print(String(data: data, encoding: .utf8) ?? "")
}
}.resume()
print("favorite")
}
func deleteFavorite(){
let user_id = defaultValues.string(forKey: "userId")
let url = URL(string: "http://example.com/api/store/favorite?")
var request = URLRequest(url: url!)
request.httpMethod = "POST"
let postParameters = "user_id=" + user_id! + "&store_id=" + storeId
request.httpBody = postParameters.data(using: .utf8)
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if error == nil, let data = data, let response = response as? HTTPURLResponse {
print("Content-Type: \(response.allHeaderFields["Content-Type"] ?? "")")
print("statusCode: \(response.statusCode)")
print(String(data: data, encoding: .utf8) ?? "")
}
}.resume()
print("delete")
}
}
Related
This question already has answers here:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Closed 4 years ago.
I have created an App using xcode 10 and use swift 4.
I am getting an error:
Fatal error: Unexpectedly found nil while unwrapping an Optional value`
I started to use NavigationController, and now I get an error. When doing Segue in the state before use, no error occurred.
I checked for Typo's etc, but there is no problem.
Error is this part
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
switch indexPath.section {
case 0 :
//Price Cell
let priceCell = tableView.dequeueReusableCell(withIdentifier: "priceCell", for: indexPath) as? priceTableViewCell
//Fatal error: Unexpectedly found nil while unwrapping an Optional value
if let price:String = store![indexPath.row].price{
priceCell?.priceLabel.text! = price
}else{
priceCell?.priceLabel.text! = "-"
}
return priceCell!
case 1 :
//timeCell
let timeCell = tableView.dequeueReusableCell(withIdentifier: "timeCell", for: indexPath) as? timeTableViewCell
if let time:String = store![indexPath.row].open_time{
timeCell?.timeLabel.text! = time
}else{
timeCell?.timeLabel.text! = "-"
}
return timeCell!
case 2 :
//closedayCell
let closedayCell = tableView.dequeueReusableCell(withIdentifier: "closedayCell", for: indexPath) as? closedayTableViewCell
if let closeday:String = store![indexPath.row].closed_day{
closedayCell?.closedayLabel.text! = closeday
}else{
closedayCell?.closedayLabel.text! = "-"
}
return closedayCell!
default :
print("Default Selected")
}
return cell
}
Store View Controller All view
import UIKit
class StoreViewController:
UIViewController,UICollectionViewDataSource,UICollectionViewDelegate,
UICollectionViewDelegateFlowLayout,UITableViewDelegate,
UITableViewDataSource {
var store_id = ""
var store : [Store]?
var photoPath : [Store.photos]?
var tag : [Store.tags]?
var selectedImage : UIImage?
let defaultValues = UserDefaults.standard
#IBOutlet weak var imageCollectionView: UICollectionView!
#IBOutlet weak var mainImage: UIImageView!
#IBOutlet weak var nameLabel: UILabel!
#IBOutlet weak var locationLabel: UILabel!
#IBOutlet weak var UIView: UIView!
#IBOutlet weak var tagCollectionView: UICollectionView!
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
//Collectiopn DetaSources
imageCollectionView.dataSource = self
imageCollectionView.delegate = self
tagCollectionView.dataSource = self
tagCollectionView.delegate = self
//UIView Shadow
let shadowPath = UIBezierPath(rect: UIView.bounds)
UIView.layer.masksToBounds = false
UIView.layer.shadowColor = UIColor.black.cgColor
UIView.layer.shadowOffset = .zero
UIView.layer.shadowOpacity = 0.2
UIView.layer.shadowPath = shadowPath.cgPath
//Request API
let url = URL(string: "http://localhost:8000/store/api?store_id=" + store_id)
let request = URLRequest(url: url!)
let session = URLSession.shared
let encoder: JSONEncoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
encoder.outputFormatting = .prettyPrinted
session.dataTask(with: request){(data, response, error)in if error == nil,
let data = data,
let response = response as? HTTPURLResponse{
let decoder: JSONDecoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
do {
let json = try decoder.decode(Store.self, from: data)
if json != nil {
print(json)
}else{
print("nil")
}
self.store = [json]
self.photoPath = json.photos
self.tag = json.tags
if let imageURL = URL(string: "http://127.0.0.1:8000/photos/" + json.photos[0].path){
DispatchQueue.global().async {
let data = try? Data(contentsOf: imageURL)
if let data = data {
let image = UIImage(data: data)
DispatchQueue.main.async {
self.mainImage.image = image
}
}
}
}
DispatchQueue.main.async {
self.nameLabel.text = json.name
self.locationLabel.text = json.location
}
} catch {
print("error:", error.localizedDescription)
}
}
}.resume()
//print(defaultValues.string(forKey: "id"))
// Image Collection view Layout
let itemSize = UIScreen.main.bounds.width/3.62 - 3.62
let layout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0)
layout.itemSize = CGSize(width: itemSize, height: itemSize)
layout.minimumInteritemSpacing = 1
layout.minimumLineSpacing = 1
imageCollectionView.collectionViewLayout = layout
// Tag Collection View
let tagLayout = UICollectionViewFlowLayout()
tagLayout.minimumLineSpacing = 1
tagLayout.minimumInteritemSpacing = 1
tagLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0)
tagLayout.itemSize = CGSize(width: 80, height: 24)
tagCollectionView.collectionViewLayout = tagLayout
print("storeID is"+store_id)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// UI coner redius
let uiViewPath = UIBezierPath(roundedRect: UIView.bounds,
byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 8, height: 8))
let uiViewMask = CAShapeLayer()
uiViewMask.path = uiViewPath.cgPath
UIView.layer.mask = uiViewMask
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Collection
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == self.imageCollectionView{
let imageCell:UICollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell",for: indexPath)
let imageView = imageCell.contentView.viewWithTag(1) as! UIImageView
let imageURL = URL(string: "http://127.0.0.1:8000/photos/" + photoPath![indexPath.row].path)
if imageURL == nil {
print("nil")
}else{
DispatchQueue.global().async {
let data = try? Data(contentsOf: imageURL!)
if let data = data {
let image = UIImage(data: data)
DispatchQueue.main.async {
imageCell.layer.masksToBounds = true;
imageCell.layer.cornerRadius = 3
imageView.image = image
}
}
}
}
return imageCell
//Tag collection view
}else if collectionView == self.tagCollectionView{
let tagCell:UICollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "Tag",for: indexPath)
let tagLabel = tagCell.contentView.viewWithTag(2) as! UILabel
tagLabel.text! = tag![indexPath.row].name
tagCell.layer.cornerRadius = 12
return tagCell
}else{
return UICollectionViewCell()
}
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return 3
}
func tagcollectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return tag?.count ?? 0
}
func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return 1
case 1 :
return 1
case 2 :
return 1
default:
return 0
}
}
//Collection view tap
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if collectionView == self.imageCollectionView{
if photoPath![indexPath.row].path != nil {
if let imageURL = URL(string: "http://127.0.0.1:8000/photos/" + photoPath![indexPath.row].path ){
DispatchQueue.global().async {
let data = try? Data(contentsOf: imageURL)
if let data = data {
let image = UIImage(data: data)
DispatchQueue.main.async {
self.mainImage.image = image
}
}
}
}
}else{
print("error")
return
}
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
switch indexPath.section {
case 0 :
//Price Cell
let priceCell = tableView.dequeueReusableCell(withIdentifier: "priceCell", for: indexPath) as? priceTableViewCell
if let price:String = store![indexPath.row].price{
priceCell?.priceLabel.text! = price
}else{
priceCell?.priceLabel.text! = "-"
}
return priceCell!
case 1 :
//timeCell
let timeCell = tableView.dequeueReusableCell(withIdentifier: "timeCell", for: indexPath) as? timeTableViewCell
if let time:String = store![indexPath.row].open_time{
timeCell?.timeLabel.text! = time
}else{
timeCell?.timeLabel.text! = "-"
}
return timeCell!
case 2 :
//closedayCell
let closedayCell = tableView.dequeueReusableCell(withIdentifier: "closedayCell", for: indexPath) as? closedayTableViewCell
if let closeday:String = store![indexPath.row].closed_day{
closedayCell?.closedayLabel.text! = closeday
}else{
closedayCell?.closedayLabel.text! = "-"
}
return closedayCell!
default :
print("Default Selected")
}
return cell
}
#IBAction func moreImageBtn(_ sender: Any) {
let store_id = self.store_id
self.performSegue(withIdentifier: "toStorePhotoViewController", sender: store_id)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toStorePhotoViewController"{
let storePhotoViewController = segue.destination as! StorePhotoViewController
storePhotoViewController.store_id = sender as! String
}
}
//Bookmark Button
#IBAction func bookmarkBtn(_ sender: Any) {
let user_id = defaultValues.string(forKey: "userId")
let url = URL(string: "http://localhost:8000/api/store/favorite?")
var request = URLRequest(url: url!)
// POSTを指定
request.httpMethod = "POST"
// POSTするデータをBodyとして設定
let postParameters = "user_id=" + user_id! + "&store_id=" + store_id
request.httpBody = postParameters.data(using: .utf8)
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if error == nil, let data = data, let response = response as? HTTPURLResponse {
// HTTPヘッダの取得
print("Content-Type: \(response.allHeaderFields["Content-Type"] ?? "")")
// HTTPステータスコード
print("statusCode: \(response.statusCode)")
print(String(data: data, encoding: .utf8) ?? "")
}
}.resume()
}
#IBAction func locationBtn(_ sender: Any) {
let lat = store![0].lat
let lng = store![0].lng
if UIApplication.shared.canOpenURL(URL(string:"comgooglemaps://")!){
let urlStr : String = "comgooglemaps://?daddr=\(lat),\(lng)&directionsmode=walking&zoom=14"
UIApplication.shared.open(URL(string:urlStr)!,options: [:], completionHandler: nil)
}else{
let daddr = String(format: "%f,%f", lat, lng)
let urlString = "http://maps.apple.com/?daddr=\(daddr)&dirflg=w"
let encodeUrl = urlString.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)!
let url = URL(string: encodeUrl)!
UIApplication.shared.open(url,options: [:], completionHandler: nil)
}
}
}
Declare array as below
var store = [Store]()
Change TableView datasource as per below:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return store.count > 0 ? 1 : 0 // if array count greater than return 1 else 0
case 1 :
return store.count > 0 ? 1 : 0
case 2 :
return store.count > 0 ? 1 : 0
default:
return 0
}
}
As mentioned by #Scriptable, You should not force unwrap.
You can add Exception break point for break point navigator like below
And then
This will help to pin point issue, Hopefully.
I am new to Swift programming
SearchBar controller with tableview. I want display the multiple students in table view its working fine. I can add the search bar controller to table view and display the particular students data. table view cell contains the student information and image I want display particular student after search
this is the code
#IBOutlet var SearchBarDisp:UISearchBar!
override func viewDidLoad()
{
super.viewDidLoad()
searchController.searchResultsUpdater = self
searchController.hidesNavigationBarDuringPresentation = false
searchController.dimsBackgroundDuringPresentation = false
tableView.tableHeaderView = searchController.searchBar
}
func updateSearchResults(for searchController: UISearchController) {
//todo
}
I can get student data from json
func getKids(url : String) {
UIApplication.shared.beginIgnoringInteractionEvents()
var errorCode = "1"
var msg = "Failed"
var request = URLRequest(url: URL(string: "getstaffstudents",
relativeTo: URL(string: serverURL+"/rkapi/api/"))!)
let session = URLSession.shared
request.httpMethod = "POST"
let bodyData = "staffId=\(staffId)"
request.httpBody = bodyData.data(using: String.Encoding.utf8);
let task = session.dataTask(with:request,completionHandler:{(d,response,error)in
do{
if let data = d {
if let jsonData = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary {
errorCode = String(describing: jsonData["errorCode"]!)
msg = jsonData["msg"] as! String
print("msg values",msg)
if errorCode == "0" {
if let kid_list = jsonData["students"] as? NSArray {
for i in 0 ..< kid_list.count {
if let kid = kid_list[i] as? NSDictionary {
kidHoleData.removeAll()
let imageURL = url+"/images/" + String(describing: kid["photo"]!)
self.kidsData.append(Kids(
studentId: kid["studentId"] as? String,
name:kid["name"] as? String,
classId : kid["classId"] as? String,
standard: ((kid["standard"] as? String)! + " " + (kid["section"] as? String)!),
photo : (imageURL),
school: kid["schoolName"] as? String,
schoolId : "1",
url : url)
)
}
}
self.loopCount += 1
self.do_table_refresh()
}
} else {
self.displayAlert("Kids", message: msg)
}
} else {
self.displayAlert("Kids", message: "Data Not Available. Please try again")
}
}else {
self.displayAlert("Kids", message: "Please try again")
}
} catch let err as NSError {
print("JSON Error \(err)")
}
})
task.resume()
}
Table view
func numberOfSections(in tableView: UITableView) -> Int {
return (kidsData.count == 0) ? 0 : 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return kidsData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell =
tableView.dequeueReusableCell(
withIdentifier: "Kidscell", for: indexPath) as! KidsTableViewCell
let maskLayer = CAShapeLayer()
let bounds = cell.bounds
maskLayer.path = UIBezierPath(roundedRect: CGRect(x: 3, y: 3, width: bounds.width-15, height: bounds.height-15), cornerRadius: 2).cgPath
cell.layer.mask = maskLayer
let row = (indexPath as NSIndexPath).row
if(kidsData.count>0){
let kid = kidsData\[row\] as Kids
cell.kidNameLabel.text = kid.name
cell.classLabel.text = kid.standard
cell.kidNameLabel.lineBreakMode = .byWordWrapping
cell.kidNameLabel.numberOfLines = 0
cell.kidImageView.image = UIImage(named: "profile_pic")
cell.kidImageView.downloadImageFrom(link: kid.photo!, contentMode: UIViewContentMode.scaleAspectFit) //set your image from link array.
}
return cell
}
I want display particular student in table view(like if I can search student name as vani it's display the student vani in table view) pls help me
copy the hole data in to the attendanceInfoDupilicate
var attendanceInfoDupilicate = [AttendanceInfo]()
Inside of the Json service call at end
self.attendanceInfoDupilicate = self.attendanceInfo
updater the search controller
func updateSearchResults(for searchController: UISearchController)
{
let searchToSeatch = AttendanceSearchBarController.searchBar.text
if(searchToSeatch == "")
{
self.attendanceInfo = self.attendanceInfoDupilicate
}
else{
self.attendanceInfo.removeAll()
let AttedanceData = self.attendanceInfoDupilicate
var kidsArray = [String]()
for AttendanceInfo in AttedanceData
{
kidsArray.append(AttendanceInfo.name)
if(AttendanceInfo.name.range(of: searchToSeatch!, options: .caseInsensitive) != nil)
{
self.attendanceInfo.append(AttendanceInfo)
}
}
}
self.TableView.reloadData()
}
This question already has an answer here:
I am getting data from json web services but unable to display it on my ui
(1 answer)
Closed 5 years ago.
here I tried to implement the collection view but unable to do it and on scroll view I had placed the collection view is it correct to implement like this if not can u provide any solution for this to display on ui and
in this scroll view has implemented on view and all the elements are placed on it here is my code and how to zoom a selected particular image also can anyone help me ?
#IBOutlet var collectionView: UICollectionView!
#IBOutlet var navigationBar: UINavigationBar!
#IBOutlet var imageView: UIImageView!
#IBOutlet var pageControl: UIPageControl!
#IBOutlet var nameLabel: UILabel!
#IBOutlet var priceLabel: UILabel!
#IBOutlet var textview: UITextView!
#IBOutlet var scrollView: UIScrollView!
var productName = [String]()
var productprice = [String]()
var productdescription :String?
var thumbnailimageArray = [String]()
var imageArray = [String]()
var pageIndex: Int = 0
var imagesArray = [String]()
let urlString = "http://www.json-generator.com/api/json/get/cjpberBhKa?indent=2"
override func viewDidLoad() {
super.viewDidLoad()
self.downloadJsonWithURL()
collectionView.delegate = self
collectionView.dataSource = self
let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(swiped(gesture:)))
swipeLeft.direction = .left
self.imageView.addGestureRecognizer(swipeLeft)
swipeLeft.cancelsTouchesInView = false
let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(swiped(gesture:)))
swipeRight.direction = .right
self.imageView.addGestureRecognizer(swipeRight)
swipeRight.cancelsTouchesInView = false
imageView.isUserInteractionEnabled = true
// Do any additional setup after loading the view.
}
func downloadJsonWithURL() {
let url = NSURL(string: urlString)
URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
print(jsonObj!.value(forKey: "Detail")!)
if let detailsArray = jsonObj!.value(forKey: "Detail") as? NSArray {
if let detailDict = detailsArray[0] as? NSDictionary {
if let name = detailDict.value(forKey: "productName") {
self.productName.append(name as! String)
}
if let image1 = detailDict.value(forKey: "image1"){
self.imageArray.append(image1 as! String)
}
if let image2 = detailDict.value(forKey: "image2"){
self.imageArray.append(image2 as! String)
}
if let image3 = detailDict.value(forKey: "image3"){
self.imageArray.append(image3 as! String)
}
if let image4 = detailDict.value(forKey: "image4"){
self.imageArray.append(image4 as! String)
}
if let image5 = detailDict.value(forKey: "image5"){
self.imageArray.append(image5 as! String)
}
if let image6 = detailDict.value(forKey: "image6"){
self.imageArray.append(image6 as! String)
}
if let image7 = detailDict.value(forKey: "image7"){
self.imageArray.append(image7 as! String)
}
if let image8 = detailDict.value(forKey: "image8"){
self.imageArray.append(image8 as! String)
}
if let image9 = detailDict.value(forKey: "image9"){
self.imageArray.append(image9 as! String)
}
if let image10 = detailDict.value(forKey: "image10"){
self.imageArray.append(image10 as! String)
}
if let price = detailDict.value(forKey: "productPrice") {
self.productprice.append(price as! String)
}
if let description = detailDict.value(forKey: "productDes") {
self.productdescription = description as? String
}
if let image = detailDict.value(forKey: "img"){
self.imagesArray.append(image as! String)
}
}
}
OperationQueue.main.addOperation({
self.navigationBar.topItem?.title = self.productName[0]
self.textview.text = self.productdescription
self.priceLabel.text = self.productprice[0]
self.nameLabel.text = self.productName[0]
print(self.imageArray)
let imgURL = NSURL(string:self.imageArray[0])
let data = NSData(contentsOf: (imgURL as URL?)!)
self.imageView.image = UIImage(data: data! as Data)
})
}
}).resume()
}
func swiped(gesture: UIGestureRecognizer) {
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.right :
if pageIndex == 0 {
}else{
pageIndex -= 1
}
let imgURL = NSURL(string:self.imageArray[pageIndex])
let data = NSData(contentsOf: (imgURL as URL?)!)
self.imageView.image = UIImage(data: data! as Data)
pageControl.numberOfPages = imageArray.count
pageControl.currentPage = pageIndex
case UISwipeGestureRecognizerDirection.left:
if pageIndex >= imageArray.count-1{
}else{
pageIndex += 1
}
let imgURL = NSURL(string:self.imageArray[pageIndex])
let data = NSData(contentsOf: (imgURL as URL?)!)
self.imageView.image = UIImage(data: data! as Data)
pageControl.numberOfPages = imageArray.count
pageControl.currentPage = pageIndex
default:
break
}
}
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return imagesArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell",for:indexPath) as! DetailsCell
let arr = imagesArray[indexPath.row]
let urls = NSURL(string: arr)
let data = NSData (contentsOf: urls! as URL)
cell.imageView.image = UIImage(data: data! as Data)
cell.nameLabel.text = self.productName[indexPath.row]
cell.priceLabel.text = self.productprice[indexPath.row]
cell.layer.borderColor = UIColor.lightGray.cgColor
cell.layer.borderWidth = 0.7
return cell
}
reload your collection view after you fetch all the data from the web service response like below.
collectionView.reloadData()
You need reload data of collectionview after downloadJsonWithURL loaded.
I am getting build errors when trying to display jSON data in Xcode using Swift 3. I am going to copy a portion of my code to this page with hopes you guys can assist me.
I have found similar questions on this site however answers don't seem to help.
class FilmsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
weak var tableView : UITableView!
var FilmArray = [String]()
let film_url = "https://www.testing.com/api/resources/films/1"
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for:indexPath) as! FilmsAPITableViewCell
// Adding the right informations
cell.movieTitle.text = FilmArray[indexPath.row]
// Returning the cell
return cell
}
// #IBOutlet weak var FilmsView: UITableView!
// weak var tableView : UITableView!
// var FilmArray = [String]()
//
// let film_url = "https://www.distribber.com/api/resources/films/1"
//
override func viewDidLoad() {
super.viewDidLoad()
let tableView = UITableView (frame:view.bounds)
view.addSubview(tableView)
self.tableView = tableView
tableView.dataSource = self
tableView.delegate = self
// func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// return 1
// }
// func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// // Getting the right element
// //let films = FilmArray[indexPath.row]
//
//
// // Instantiate a cell
// //let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "moviecell")
// let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! FilmsAPITableViewCell
// // cell.movieTitle.text = FilmArray[indexPath.row]
// // Adding the right informations
// cell.movieTitle.text = FilmArray[indexPath.row]
// // Returning the cell
// return cell
// }
// }
//}
let url:URL = URL(string: film_url)!
let session = URLSession.shared
let request = NSMutableURLRequest(url: url)
request.httpMethod = "GET"
request.setValue("740c94c51891c02b64d6c78840b478fe0b02fe2c", forHTTPHeaderField: "X-API-KEY")
request.setValue("Basic YmhlZW0uZW5nckBnbWFpbC5jb206YmgzM20=", forHTTPHeaderField: "Authorization")
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
let paramString = ""
// for (key, value) in post_data
// {
// paramString = paramString + (key as! String) + "=" + (value as! String) + "&"
// }
//
request.httpBody = paramString.data(using: String.Encoding.utf8)
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(
data, response, error) in
guard let _:Data = data, let _:URLResponse = response , error == nil else {
return
}
let json: Any?
do
{
json = try JSONSerialization.jsonObject(with: data!, options: [])
// Prasing JSON
var parsedData = try JSONSerialization.jsonObject(with: data!, options: []) as! [String:Any]
print(parsedData)
if let FilmArray = parsedData["films"] as? NSArray {
for movieTitle in FilmArray{
if let filmDict = movieTitle as? NSDictionary{
if let film = filmDict.value(forKey: "title") {
self.FilmArray.append(film as! String)
}
OperationQueue.main.addOperation({
self.tableView.reloadData()
})
}
}
}
print("Hello")
self.tableView.reloadData()
print(self.FilmArray)
}
catch
{
return
}
guard let server_response = json as? NSDictionary else
{
return
}
if let data_block = server_response["data"] as? NSDictionary
{
if let session_data = data_block["session"] as? String
{
// self.login_session = session_data
let preferences = UserDefaults.standard
preferences.set(session_data, forKey: "session")
// DispatchQueue.main.async(execute: self.LoginDone)
}
}
})
task.resume()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Here is also output from FilmsAPITableViewCell.swift
import UIKit
import UIKit
class FilmsAPITableViewCell: UITableViewCell {
#IBOutlet weak var movieTitle: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
The reason why movieTitle is nil is because your custom cell class does not have that label outlet. You need to create a UILabel in your .xib (or storyboard) and create an outlet connection inside your custom cell class.
It also seems like no self.tableView.reloadData() exists in your completion block. Try adding that right after the print("Hello") line.
P.S. Don't forget to dispatch the reload to the main queue.
Here is also your code which I edited as to get it working:
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
let url:URL = URL(string: film_url)!
let session = URLSession.shared
let request = NSMutableURLRequest(url: url)
request.httpMethod = "GET"
request.setValue("740c94c51891c02b64d6c78840b478fe0b02fe2c", forHTTPHeaderField: "X-API-KEY")
request.setValue("Basic YmhlZW0uZW5nckBnbWFpbC5jb206YmgzM20=", forHTTPHeaderField: "Authorization")
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
let paramString = ""
request.httpBody = paramString.data(using: String.Encoding.utf8)
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(
data, response, error) in
guard let _:Data = data, let _:URLResponse = response , error == nil else {
return
}
var json:Any?
do
{
if let existingData = data {
json = try JSONSerialization.jsonObject(with: existingData, options: [])
}
// Prasing JSON
if let parsedData = json as? [[String:Any]] {
for dict in parsedData {
if let title = dict["title"] as? String {
self.FilmArray.append(title)
}
}
OperationQueue.main.addOperation({
self.tableView.reloadData()
})
}
}
catch
{
return
}
guard let server_response = json as? NSDictionary else
{
return
}
if let data_block = server_response["data"] as? NSDictionary
{
if let session_data = data_block["session"] as? String
{
// self.login_session = session_data
let preferences = UserDefaults.standard
preferences.set(session_data, forKey: "session")
// DispatchQueue.main.async(execute: self.LoginDone)
}
}
})
task.resume()
}
import UIKit
import Alamofire
protocol VideoModelDelegate{
func dataReady()
}
class VideoModel: NSObject {
let API_KEY = ""
let UPLOADS_PLAYLIST_ID = ""
var videoArray = [Video]()
var delegate:VideoModelDelegate?
func getFeedVideos() -> [Video] {
Alamofire.request(.GET, "",parameters: ["part":"snippet", "playlistId":UPLOADS_PLAYLIST_ID ,"key":API_KEY],
encoding: ParameterEncoding.URL, headers: nil).responseJSON {(response) -> Void in
if let JSON = response.result.value{
var arrayOfVideos = [Video]()
for video in JSON["items"] as! NSArray {
print(video)
let videoObj = Video()
videoObj.videoId = video.valueForKeyPath("snippet,resourceId, videoId")
String
videoObj.videoTitle = video.valueForKeyPath("snippet.title") as! String
videoObj.videoDescription = video.valueForKeyPath("snippet.description") as!
String
videoObj.videoThumbnailUrl = video.valueForKeyPath("snippet.thumbnails.maxres.url") as! String
arrayOfVideos.append(videoObj)
}
self.videoArray = arrayOfVideos
if self.delegate != nil {
self.delegate!.dataReady()
}
}
}
}
func getVideos() -> [Video] {
var videos = [Video]()
let video1 = Video()
video1.videoId = ""
video1.videoTitle = ""
videos.append(video1)
return videos
}
}
[Additional Errors][Error]1How to make my viewcontroller conform to protocol "UITableViewDataSource, and Video Mode Delegate"?
I have tried a number of suggested changes in the previous threads, but nothing got me through, Please help me out.
Thanks in advance
import UIKit
import Alamofire
class tab: UIViewController, UITableViewDataSource,
UITableViewDelegate, VideoModelDelegate ERROR- Type 'tab' does not conform to protocol 'UITableViewDataSource'
{
#IBOutlet weak var table: UITableView!
#IBOutlet weak var name: UILabel!
var videos : [Video] = [Video]()
var selectedVideo:Video?
let model:VideoModel = VideoModel()
var arrRes = [[String:AnyObject]]() //Array of dictionary
override func viewDidLoad() {
super.viewDidLoad()
self.model.delegate = self
//self.videos = model.getVideos()
model.getFeedVideos()
self.table.dataSource = self
self.table.delegate = self
/*Alamofire.request(.GET, "http://online.m-tutor.com/mtutor/gateway/mtutorAPI_1.php?type=university").response { (req, res, data, error) -> Void in
print(res)
let outputString = NSString(data: data!, encoding:NSUTF8StringEncoding)
print(outputString)
}
Alamofire.request(.GET, "http://online.m-tutor.com/mtutor/gateway/mtutorAPI_1.php?type=university").responseJSON { response in
if let swiftyJsonVar = response.data
{
print("swiftyJsonvar:\(swiftyJsonVar)")
}
}*/
Alamofire.request(.GET, "http://online.m-tutor.com/mtutor/gateway/mtutorAPI_1.php?type=university").responseJSON { (responseData) -> Void in
let swiftyJsonVar = JSON(responseData.result.value!)
if let resData = swiftyJsonVar["contacts"].arrayObject {
self.arrRes = resData as! [[String:AnyObject]]
}
if self.arrRes.count > 0 {
self.table.reloadData()
}
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
func dataReady(){
self.videos = self.model.videoArray
self.table.reloadData()
}
func tableView(table: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) ->
CGFloat {
return(self.view.frame.size.width / 320) * 180
}
func tableview(table:UITableView, numberOfRowsInSection section: Int ) ->Int{
return videos.count
}
func tableVie(table: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->
UITableViewCell{
let cell = table.dequeueReusableCellWithIdentifier("jsonCell")!
let videoTitle = videos[indexPath.row].videoTitle
let label = cell.viewWithTag(2) as! UILabel
label.text = videoTitle
//cell.textLabel?.text = videoTitle
let videoThumbnailUrlString =
videos[indexPath.row].videoThumbnailUrlString;)ERROR:Expected Expression
let videoThumbnailUrl != nil ERROR-'!= is not a prefix unary operator'
and 'Type annotation missing in pattern'
{
let request = NSURLRequest(URL: videoThumbnailUrl!)
let session = NSURLSession.sharedSession()
let dataTask = session.dataTaskWithRequest(request, completionHandler: {(data:NSData?, response:NSURLResponse?, error:NSError) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let imageView = cell.viewWithTag(1) as! UIImageView
imageView.image = UIImage(data: data!)
})
})
dataTask.resume()
}
return cell
func tableView(table: UITableView, didSelectRowAtIndexPath indexpath: NSIndexPath){
self.selectedVideo = self.videos[indexpath.row]
self.performSegueWithIdentifier("toVDVC", sender: self)
}
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){
let detailViewController = segue.destinationViewController as! VDViewController
detailViewController.selectedVideo = self.selectedVideo
}
}
}
}
re
It looks as though you haven't closed the method didReceivedMemoryWarning: and the tableview delegate methods are then effectively inside this method causing your issue. Add a closing bracket and it should be fine:
Update: Here is the updated code. There was some more formatting issues with brackets and an error with your if statement in the cellForRowAtIndex:
import UIKit
import Alamofire
class tab: UIViewController, UITableViewDataSource, UITableViewDelegate, VideoModelDelegate {
#IBOutlet weak var table: UITableView!
#IBOutlet weak var name: UILabel!
var videos : [Video] = [Video]()
var selectedVideo:Video?
let model:VideoModel = VideoModel()
var arrRes = [[String:AnyObject]]() //Array of dictionary
override func viewDidLoad() {
super.viewDidLoad()
self.model.delegate = self
//self.videos = model.getVideos()
model.getFeedVideos()
self.table.dataSource = self
self.table.delegate = self
/*Alamofire.request(.GET, "http://online.m-tutor.com/mtutor/gateway/mtutorAPI_1.php?type=university").response { (req, res, data, error) -> Void in
print(res)
let outputString = NSString(data: data!, encoding:NSUTF8StringEncoding)
print(outputString)
}
Alamofire.request(.GET, "http://online.m-tutor.com/mtutor/gateway/mtutorAPI_1.php?type=university").responseJSON { response in
if let swiftyJsonVar = response.data
{
print("swiftyJsonvar:\(swiftyJsonVar)")
}
}*/
Alamofire.request(.GET, "http://online.m-tutor.com/mtutor/gateway/mtutorAPI_1.php?type=university").responseJSON { (responseData) -> Void in
let swiftyJsonVar = JSON(responseData.result.value!)
if let resData = swiftyJsonVar["contacts"].arrayObject {
self.arrRes = resData as! [[String:AnyObject]]
}
if self.arrRes.count > 0 {
self.table.reloadData()
}
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
} //ADDED CLOSING BRACKET HERE
func dataReady(){
self.videos = self.model.videoArray
self.table.reloadData()
}
func tableView(table: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) ->
CGFloat {
return(self.view.frame.size.width / 320) * 180
}
func tableview(table:UITableView, numberOfRowsInSection section: Int ) ->Int{
return videos.count
}
func tableVie(table: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->
UITableViewCell{
let cell = table.dequeueReusableCellWithIdentifier("jsonCell")!
let videoTitle = videos[indexPath.row].videoTitle
let label = cell.viewWithTag(2) as! UILabel
label.text = videoTitle
//cell.textLabel?.text = videoTitle
//CHANGE THESE TWO LINES:
//let videoThumbnailUrlString = videos[indexPath.row].videoThumbnailUrlString;)
//if let videoThumbnailUrl != nil {
//TO THIS:
if let videoThumbnailUrl = videos[indexPath.row].videoThumbnailUrlString {
let request = NSURLRequest(URL: videoThumbnailUrl!)
let session = NSURLSession.sharedSession()
let dataTask = session.dataTaskWithRequest(request, completionHandler: {(data:NSData?, response:NSURLResponse?, error:NSError) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let imageView = cell.viewWithTag(1) as! UIImageView
imageView.image = UIImage(data: data!)
})
})
dataTask.resume()
}
return cell
}
func tableView(table: UITableView, didSelectRowAtIndexPath indexpath: NSIndexPath){
self.selectedVideo = self.videos[indexpath.row]
self.performSegueWithIdentifier("toVDVC", sender: self)
}
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){
let detailViewController = segue.destinationViewController as! VDViewController
detailViewController.selectedVideo = self.selectedVideo
}
}