Как проверить на пустое поле с помощью музыкальных данных перед заполнением таблиц?IOS

Программируем под IOS
Ответить Пред. темаСлед. тема
Anonymous
 Как проверить на пустое поле с помощью музыкальных данных перед заполнением таблиц?

Сообщение Anonymous »

Следующий код будет сбоем в строке numofrowspersection = Query.collectionsections! Если все поля художника заполнены данными (Ex: Beatles), то нет никакого сбоя. Я безуспешно пытался проверить на нуле. Это может быть мое отсутствие понимания «опционов» и т. Д.import UIKit
import MediaPlayer

// ********** Main Class **********
class ArtistsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

var query = MPMediaQuery.songs()

var selectedArtist: String! // This value will be set below.
var selectedArtistPersistentID: UInt64! // This value will be set below.

var rowNumInSectionWhereArtistWasFound = 0
var sectionNumOfSectionWhereArtistWasFound = 0

var nowPlayingButtonClicked: Bool = false // This value will be set below.

var myMPMusicPlayerController = MPMusicPlayerController.systemMusicPlayer
var notificationCenter = NotificationCenter.default

override func viewDidLoad() {
super.viewDidLoad()

query.groupingType = MPMediaGrouping.artist // Causes the songs query to be a list of Artists
}

//---------------------------------------------------------------------------------------------------------------------
// Display the index of the table on the right-hand side of the screen
func sectionIndexTitles(for tableView: UITableView) -> [String]? {

let sectionIndexTitlesArray = query.itemSections!.map { $0.title }
return sectionIndexTitlesArray
}

// Set the alignment of the section header in the table
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {

let header = view as! UITableViewHeaderFooterView
header.textLabel!.textAlignment = NSTextAlignment.center
}

// Get the index of the section when the user touches the index column on the right handside of the table
func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {

let indexOfTouch = index
return indexOfTouch
}

// Display a header title in each section
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

let headerTitle = query.itemSections![section].title
return headerTitle
}

// Get the number of sections
func numberOfSections(in tableView: UITableView) -> Int {

let numOfSections = query.itemSections!.count
return numOfSections
}

// Get the number of rows per Section - YES SECTIONS EXIST WITHIN QUERIES
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

let numOfRowsPerSection = query.collectionSections![section].range.length. // CRASHES, if Artists field is empty!!!
return numOfRowsPerSection
}

// Set the cell in the table
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

// I am using the custom class that I created called: myCell
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) as! myTableViewCell

let currLoc = query.collectionSections![indexPath.section].range.location
let rowItem = query.collections![indexPath.row + currLoc]

// Get the album artwork...
let albumArtwork = rowItem.representativeItem?.artwork
// Test the album artwork... note that my first 2 playlists don't have an image, so I believe the following test works.
if albumArtwork != nil {
// Xcode/Swift encouraged me to put the CGSize of 44, 44; just in case nil was found. But I don't think nil can be found because I just tested for it.
cell.cover.image = albumArtwork?.image(at: albumArtwork?.bounds.size ?? CGSize(width: 44, height: 44))
} else {
cell.cover.image = UIImage(named:"MusicalNote")!
}

// Main text is Artist name
cell.title.text = rowItem.items[0].artist

// Set the sub text as the list of albums by the artist in the current row.
// Query the albums
let qryAlbums = MPMediaQuery.albums()

// Filter the Albums by the Artist in the current row.
let predicateByArtist = MPMediaPropertyPredicate(value: rowItem.items[0].artist, forProperty: MPMediaItemPropertyArtist)
qryAlbums.filterPredicates = NSSet(object: predicateByArtist) as? Set

// Get the total number of albums by this artist.
let total = qryAlbums.collections!.count

// Get all the album titles for this artist.
var albumTitles = ""
var foundAlbumTitle = ""
for i in 0 ..< total {
foundAlbumTitle = qryAlbums.collections!.items[0].albumTitle ?? "Missing title"
if i == 0 {
albumTitles = foundAlbumTitle
} else {
albumTitles = albumTitles + "; " + foundAlbumTitle
}
}
cell.subTitle.text = albumTitles

return cell
}
//---------------------------------------------------------------------------------------------------------------------

}


Подробнее здесь: https://stackoverflow.com/questions/796 ... -in-tables
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «IOS»