how to pass data to buttons through an array in swift - ios

I am trying to fetch data from the database to a slide menu. I am using the following code for fetching the data and need to connect to buttons in the buttons present in the UI.
func fetchiingcontact()
{
var allusers:NSMutableArray = NSMutableArray()
allusers = ModelManager.getInstance().getAlldrawerData()//Fetching contacts objects from Sqlite
for var i = 0 ; i < allusers.count ; i++
{
var userobject : user = user()
userobject = allusers.objectAtIndex(i) as! user
let contactobjectuser:UserContactsClass = UserContactsClass()
let userdefault = NSUserDefaults.standardUserDefaults()
let ownuserid = userdefault.integerForKey("Userid")
if(userobject.userid == ownuserid)
{
}
else
{
contactobjectuser.firstName = userobject.firstName
contactobjectuser.lastName = userobject.lastName
contactobjectuser.profilePic = userobject.profilePic
contactobjectuser.nickName = userobject.nickName
usercontactslistarray.addObject(contactobjectuser)
self.secondLabel.text = contactobjectuser.lastName
self.userFlname.text = contactobjectuser.firstName
}
}
how do i connect the usercontactslistarray to the ui buttons by code as self.secondlabel.text is not working

You can use
self. userFlname.setText(contactobjectuser.lastName)
self.secondLabel.setText(contactobjectuser.lastName)

let string = "Your Text"
yourButton.setTitle(string as String, forState: UIControlState.Normal)

Related

Taking so much time when i insert 10k data in coredata ?

In my project concept i need a insert 10k data when user open the application. I integrate core data for storing data but its take 1 to 5 minutes.
Here is my code ?
func inserChatMessage(_ message: String, chatId: String, onCompletion completionHandler:((_ message: ChatMessage) -> Void)?) {
var objMessage: ChatMessage? = nil
if let obj = ChatMessage.createEntity() {
objMessage = obj
}
objMessage?.messageId = ""
objMessage?.message = message
objMessage?.chatId = chatId
objMessage?.senderId = AIUser.current.userId
objMessage?.createAt = Date()
objMessage?.updateAt = Date()
let cManager = CoreDataManager.sharedManager
cManager.saveContext()
if let completionHandler = completionHandler, let objMessage = objMessage {
completionHandler(objMessage)
}
}
Coredata is not a threadsafe. And as per your requirement you need to save large amount of data on app launch. So If you will save those data using main thread, your app will get hanged. So Instead on saving large amount of data on main thread you can save those data on background thread. Coredata is supporting multi threading concept by providing parent child context concept.
I have done same in one of my project and its working fine. Here i have attached code.
func savePersonalMessagesOnBackGroundThread(arrMessages:NSArray,responseData:#escaping () -> Void)
{
print(arrMessages)
let temporaryChatContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType)
temporaryChatContext.parent = self.managedObjectContext
temporaryChatContext.perform({() -> Void in
for i in 0..<arrMessages.count
{
let msgDic = arrMessages[i] as! NSDictionary
_ = self.saveMessageInLocalDB(dictMessage: msgDic, managedObjectContext: temporaryChatContext, onBackground: true)
if i == arrMessages.count - 1 {
do {
try temporaryChatContext.save()
runOnMainThreadWithoutDeadlock {
DLog(message: "Thred \(Thread.isMainThread)")
if(self.managedObjectContext.hasChanges)
{
self.saveContext()
responseData()
}
}
}
catch {
print(error)
}
}
}
})
}
func saveMessageInLocalDB(dictMessage:NSDictionary, managedObjectContext:NSManagedObjectContext,onBackground:Bool) -> Chat
{
var chatObj : Chat! = Chat()
var receiveId: Int32!
var flag:Bool = false
print(dictMessage)
// let predicate = NSPredicate(format:"uniqueId == %# and senderId = %d and receiverId = %d","\(dictMessage.value(forKey:keyuniqueId)!)",Int32(dictMessage.value(forKey:keysenderId) as! Int64),Int32(dictMessage.value(forKey:keyreceiverId) as! Int64))
let predicate = NSPredicate(format:"uniqueId == %#","\(dictMessage.value(forKey:keyuniqueId)!)")
let objContext = managedObjectContext
let fetchRequest = NSFetchRequest<Chat>(entityName: ENTITY_CHAT)
let disentity: NSEntityDescription = NSEntityDescription.entity(forEntityName: ENTITY_CHAT, in: objContext)!
fetchRequest.predicate = predicate
fetchRequest.entity = disentity
do{
let results = try managedObjectContext.fetch(fetchRequest as! NSFetchRequest<NSFetchRequestResult>) as! [Chat]
if(results.count > 0)
{
chatObj = results[0]
chatObj.messageId = Int32(dictMessage.value(forKey:keymessageId) as! Int64)
chatObj.dateOnly = dictMessage.value(forKey:keydateOnly) as! String?
}
else{
//receiveId = Int32(dictMessage.value(forKey:keyreceiverId) as! Int64)
//self.createNewChatObject(dictMessage: dictMessage, receiverId: receiveId, managedObjectContext: managedObjectContext)
chatObj = NSEntityDescription.insertNewObject(forEntityName:ENTITY_CHAT,into: managedObjectContext) as? Chat
if dictMessage[keymessageId] != nil {
chatObj.messageId = dictMessage.value(forKey:keymessageId) as! Int32
}
if(chatObj.message?.length != 0)
{
chatObj.message = dictMessage.value(forKey:keychatMessage) as? String
}
chatObj.messageType = Int32(dictMessage.value(forKey:keymessageType) as! Int64)
chatObj.senderId = Int32(dictMessage.value(forKey:keysenderId) as! Int64)
if(chatObj.senderId != Int32((APP_DELEGATE.loggedInUser?.id!)!))
{
let contactObj = self.getContactByContactId(contactId: Int32(dictMessage.value(forKey:keysenderId) as! Int64))
if(contactObj == nil)
{
_ = self.saveUnknownUserASContact(msgDict: dictMessage as! Dictionary<String, Any>)
}
}
chatObj.receiverId = Int32(dictMessage.value(forKey:keyreceiverId) as! Int64)
chatObj.uniqueId = dictMessage.value(forKey:keyuniqueId) as? String
chatObj.mediaName = dictMessage.value(forKey:keymediaName) as? String
print(NSDate())
if dictMessage[keycreatedDate] != nil {
let utcDate : NSDate = DateFormater.getUTCDateFromUTCString(givenDate: dictMessage.value(forKey:keycreatedDate) as! String)
chatObj.createdDate = utcDate
chatObj.updatedDate = utcDate
}
else
{
chatObj.createdDate = NSDate()
chatObj.updatedDate = NSDate()
}
if(chatObj.senderId == Int32((APP_DELEGATE.loggedInUser?.id)!))
{
chatObj.chatUser = chatObj.receiverId
}
else
{
chatObj.chatUser = chatObj.senderId
}
if dictMessage[keystatus] != nil {
chatObj.status = Bool((dictMessage.value(forKey:keystatus) as! Int64) as NSNumber)
}
switch Int(chatObj.messageType)
{
case MSG_TYPE.MSG_Text.rawValue:
chatObj.cellType = (chatObj.senderId != Int32((APP_DELEGATE.loggedInUser?.id!)!) ? Int32(CELL_TYPE.CELL_TEXT_RECEIVER.rawValue) : Int32(CELL_TYPE.CELL_TEXT_SENDER.rawValue))
case MSG_TYPE.MSG_Image.rawValue:
chatObj.cellType = (chatObj.senderId != Int32((APP_DELEGATE.loggedInUser?.id!)!) ? Int32(CELL_TYPE.CELL_IMAGE_RECEIVER.rawValue) : Int32(CELL_TYPE.CELL_IMAGE_SENDER.rawValue))
self.saveMedia(chatObj: chatObj)
default :
// chatObj.cellType = Int32(CELL_TYPE.CELL_LOAD_MORE.rawValue)
break
}
}
// deviceMake = 1;
if(!onBackground)
{
self.saveContext()
}
}
catch
{
}
return chatObj
}
Using the basic example below I can insert 10k records very quickly. The main thing that has changed here compared to your code is that I loop through and create the entities and then call save() at the very end. So you are performing one write call to the db instead of 10k. You are writing more information in that one call but it is still much quicker.
import UIKit
import CoreData
class ViewController: UIViewController {
lazy var sharedContext: NSManagedObjectContext? = {
return (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext
}()
override func viewDidLoad() {
super.viewDidLoad()
if let messages = getMessages(), messages.count > 0 {
printMessages(messages: messages)
} else {
loadChatMessages()
printMessages(messages: getMessages())
}
}
private func printMessages(messages: [Message]?) {
guard let messages = messages else { return }
for message in messages {
print(message.message)
}
}
private func getMessages() -> [Message]? {
let request = NSFetchRequest<Message>(entityName: "Message")
let messages = try? self.sharedContext?.fetch(request)
return messages ?? nil
}
private func loadChatMessages() {
var counter = 1
while counter <= 10000 {
let message = Message(entity: Message.entity(), insertInto: self.sharedContext)
message.message = "This is message number \(counter)"
message.read = false
message.timestamp = Date()
counter = counter + 1
}
do {
try self.sharedContext?.save()
} catch {
print(error)
}
}
}
As mentioned in my comment above, you can improve this further by doing it in the background (see Twinkle's answer for an example of how to switch to a background thread), you can also provide a pre-filled (pre-seeded) core data database that already contains the 10k records with your app. so it doesn't need to load this on initial load.
To do this you would fill the db locally on your dev machine and then copy it to the project bundle. On initial load you can check to see if your db filename exists in the documents folder or not. If it doesn't copy it over from the bundle and then use that DB for core data.

Swift display annotations in mapView in another thread

This code does not add annotations to mapView. I saw in one answer that mapView function is called every time addAnotation is called so where's the problem? But when I move map they show up.
func addPlacesMarkers(location:CLLocation) {
self.communication.getJsonData(self.getPubsNearByCreator(location)) { (finalData, error) -> Void in
if error != nil {
print(error)
} else {
if let row: NSArray = finalData {
for var i = 0; i < row.count; i++ {
let lat = row[i]["lat"] as! String
let lng = row[i]["lng"] as! String
let title = row[i]["name"] as! String
let id = row[i]["id"] as! String
let point = CustomizedAnotation(id: Int(id)!, name: title)
point.title = title
point.coordinate.latitude = Double(lat)!
point.coordinate.longitude = Double(lng)!
let keyExists = self.places[Int(id)!] != nil
if keyExists == false {
self.places.updateValue(point, forKey: Int(id)!)
}
}
var finalPlaces :[MKPointAnnotation] = []
for place in self.places.values {
finalPlaces.append(place)
}
self.mView.addAnnotations(finalPlaces)
self.mView.showsPointsOfInterest = false
}
}
}
}
You can't modify the UI in a thread different from the main.
You should put your UI modification code inside a dispatch_async block like this:
dispatch_async(dispatch_get_main_queue()) {
//Your code that modify the UI
self.mView.addAnnotations(finalPlaces)
}

Memory leak issue iOS NSCFString

Original code using join() shows a memory leak in Instruments. I used a loop instead and it seems to have fixed the issue. Curious if this seems to be a framework issue?
//in ViewDidLoad
let saveButton = UIBarButtonItem(barButtonSystemItem: .Save, target: self, action: "saveBtnAc")
self.navigationItem.rightBarButtonItem = saveButton
//end ViewDidLoad
//using a loop to join the string instead of join()
func doJndString(theArray: [String]) -> String {
var updatedAryJnd = String()
var count = 0
let lastItemCount = theArray.count - 1
while (count < lastItemCount) {
updatedAryJnd += (theArray[count] + "§")
count++
}
updatedAryJnd += theArray[lastItemCount]
return updatedAryJnd
}
//button action
func saveBtnAc() {
var myAry = [""]
if let items1 = setupItem?.valueForKey("itemsAry1") as? String {
myAry = items1.componentsSeparatedByString("§")
}
myAry[itemClkdVar] = myTxtOutlet.text
//I get a leak when using the following join()
//let updatedAryJnd = "§".join(myAry)
//setupItem!.setValue(updatedAryJnd, forKey: "itemsAry1")
//change above to this and no leak
setupItem!.setValue(doJndString(myAry), forKey: "itemsAry1")
var error: NSError? = nil
if !contextOb!.save(&error) {
println("had an error")
}
}

Refactor cellForRowIndexPath in UITableView Swift

I have a rather long cellForRowAtIndexPath function. I am using parse as my backend and have a lot going on. I want to extract a lot of these conditions and put them in their own functions. Especially the PFUser query, but unfortunately I don't know whats the best way to go about it since I don't know how I can access the elements of each cell in those functions I want to write.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("PostCells", forIndexPath: indexPath) as! NewsFeedTableCellTableViewCell
// Configure the cell...
// A drive is a post
let drive: PFObject = self.timelineData[indexPath.row] as PFObject
var driverId = drive.objectForKey("driver")!.objectId!
var currentUserObjectId = PFUser.currentUser()!.objectId
if(driverId != currentUserObjectId){
cell.requestButton.layer.borderWidth = 1
cell.requestButton.titleLabel!.font = UIFont.systemFontOfSize(11)
cell.requestButton.tintColor = UIColor.orangeColor()
cell.requestButton.layer.borderColor = UIColor.orangeColor().CGColor
cell.requestButton.setTitle("REQUEST", forState: UIControlState.Normal)
}
else {
cell.requestButton.layer.borderWidth = 1
cell.requestButton.titleLabel!.font = UIFont.systemFontOfSize(11)
cell.requestButton.tintColor = UIColor.grayColor()
cell.requestButton.layer.borderColor = UIColor.lightGrayColor().CGColor
cell.requestButton.setTitle("REQUEST", forState: UIControlState.Normal)
cell.requestButton.enabled = false
}
// Setting up the attributes of the cell for the news feed
cell.driveTitleTextField.text = drive.objectForKey("title") as! String
cell.wayTextField.text = drive.objectForKey("way") as! String
var departureDate = NSDate()
departureDate = drive.objectForKey("departureDate") as! NSDate
var dateFormat = NSDateFormatter()
dateFormat.dateFormat = "M/dd hh:mm a"
cell.departureDateTextField.text = dateFormat.stringFromDate(departureDate)
if((drive.objectForKey("way")!.isEqualToString("Two Way")))
{
var returnDate = NSDate()
returnDate = drive.objectForKey("returnDate") as! NSDate
cell.returningDateTextField.text = dateFormat.stringFromDate(returnDate)
}
else if((drive.objectForKey("way")!.isEqualToString("One Way")))
{
cell.returningDateTextField.enabled = false
cell.returningDateTextField.userInteractionEnabled = false
cell.returningDateTextField.hidden = true
cell.returningLabel.hidden = true
}
var seatNumber = NSNumber()
seatNumber = drive.objectForKey("seatNumber") as! NSInteger
var numberFormat = NSNumberFormatter()
numberFormat.stringFromNumber(seatNumber)
cell.seatNumberTextField.text = numberFormat.stringFromNumber(seatNumber)
// this is a PFUser query so we can get the users image and name and email from the User class
var findDrive = PFUser.query()
var objectId: AnyObject? = drive.objectForKey("driver")!.objectId!
findDrive?.whereKey("objectId", equalTo: objectId!)
findDrive?.findObjectsInBackgroundWithBlock{
(objects:[AnyObject]?, error:NSError?)->Void in
if (error == nil){
if let actualObjects = objects {
let possibleUser = (actualObjects as NSArray).lastObject as? PFUser
if let user = possibleUser {
cell.userProfileNameLabel.text = user["fullName"] as? String
cell.userEmailLabel.text = user["username"] as? String
//Profile Image
cell.profileImage.alpha = 0
if let profileImage = user["profilePicture"] as? PFFile {
profileImage.getDataInBackgroundWithBlock{
(imageData:NSData? , error:NSError?)-> Void in
if(error == nil) {
if imageData != nil{
let image:UIImage = UIImage (data: imageData!)!
cell.profileImage.image = image
}
}
}
}
UIView.animateWithDuration(0.5, animations: {
cell.driveTitleTextField.alpha = 1
cell.wayTextField.alpha = 1
cell.profileImage.alpha = 1
cell.userProfileNameLabel.alpha = 1
cell.userEmailLabel.alpha = 1
cell.seatNumberTextField.alpha = 1
cell.returningDateTextField.alpha = 1
cell.departureDateTextField.alpha = 1
})
}
}
}
}
return cell
}
EDIT 1
I came up with a way to refactor my code that I would like critiqued!
1. I extracted a lot of the cells configurations and put them into to functions, one for the button on the cell and the other for all the data from parse.
func configureDataTableViewCell(cell:NewsFeedTableCellTableViewCell, drive: PFObject)
{
cell.driveTitleTextField.text = drive.objectForKey("title") as! String
cell.wayTextField.text = drive.objectForKey("way") as! String
cell.userEmailLabel.text = drive.objectForKey("username") as? String
cell.userProfileNameLabel.text = drive.objectForKey("name") as? String
var departureDate = NSDate()
departureDate = drive.objectForKey("departureDate") as! NSDate
var dateFormat = NSDateFormatter()
dateFormat.dateFormat = "M/dd hh:mm a"
cell.departureDateTextField.text = dateFormat.stringFromDate(departureDate)
if((drive.objectForKey("way")!.isEqualToString("Two Way")))
{
var returnDate = NSDate()
returnDate = drive.objectForKey("returnDate") as! NSDate
cell.returningDateTextField.text = dateFormat.stringFromDate(returnDate)
}
else if((drive.objectForKey("way")!.isEqualToString("One Way")))
{
cell.returningDateTextField.enabled = false
cell.returningDateTextField.userInteractionEnabled = false
cell.returningDateTextField.hidden = true
cell.returningLabel.hidden = true
}
var seatNumber = NSNumber()
seatNumber = drive.objectForKey("seatNumber") as! NSInteger
var numberFormat = NSNumberFormatter()
numberFormat.stringFromNumber(seatNumber)
cell.seatNumberTextField.text = numberFormat.stringFromNumber(seatNumber)
}
func configureButtonTableViewCell(cell:NewsFeedTableCellTableViewCell, userID: String)
{
var currentUserObjectId = PFUser.currentUser()!.objectId
if(userID != currentUserObjectId){
cell.requestButton.layer.borderWidth = 1
cell.requestButton.titleLabel!.font = UIFont.systemFontOfSize(11)
cell.requestButton.tintColor = UIColor.orangeColor()
cell.requestButton.layer.borderColor = UIColor.orangeColor().CGColor
cell.requestButton.setTitle("REQUEST", forState: UIControlState.Normal)
println("orange")
}
else {
cell.requestButton.layer.borderWidth = 1
cell.requestButton.titleLabel!.font = UIFont.systemFontOfSize(11)
cell.requestButton.tintColor = UIColor.grayColor()
cell.requestButton.layer.borderColor = UIColor.lightGrayColor().CGColor
cell.requestButton.setTitle("REQUEST", forState: UIControlState.Normal)
cell.requestButton.enabled = false
println("gray")
}
}
2. I then passed in the functions from step 1 and into my cellForRowIndexPath
// A drive is a post
let drive: PFObject = self.timelineData[indexPath.row] as PFObject
var driverId : String = drive.objectForKey("driver")!.objectId!!
configureButtonTableViewCell(cell, userID: driverId)
configureDataTableViewCell(cell, drive: drive)
3. I stored all my PFUser data into my object when its saved instead of querying the user class. So I get the PFUser.currentUser() username, full name, and profile picture when they save a post.
My load data has been modified. I store all the profile pictures in there own array.
func loadData(){
var findItemData:PFQuery = PFQuery(className:"Posts")
findItemData.addDescendingOrder("createdAt")
findItemData.findObjectsInBackgroundWithBlock{
(objects:[AnyObject]? , error:NSError?) -> Void in
if error == nil
{
self.timelineData.removeAll(keepCapacity: false)
self.profilePictures.removeAll(keepCapacity: false)
self.timelineData = objects as! [PFObject]
for object in objects! {
self.profilePictures.append(object.objectForKey("profilePicture") as! PFFile)
}
self.newsFeedTableView.reloadData()
}
}
}
And finally, here is my updated cellForRowIndexPath
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("PostCells", forIndexPath: indexPath) as! NewsFeedTableCellTableViewCell
// Configure the cell...
// A drive is a post
let drive: PFObject = self.timelineData[indexPath.row] as PFObject
var driverId : String = drive.objectForKey("driver")!.objectId!!
configureButtonTableViewCell(cell, userID: driverId)
configureDataTableViewCell(cell, drive: drive)
println(PFUser.currentUser()?.objectForKey("username"))
if let profileImage = drive["profilePicture"] as? PFFile {
profileImage.getDataInBackgroundWithBlock{
(imageData:NSData? , error:NSError?)-> Void in
if(error == nil) {
if imageData != nil{
let image:UIImage = UIImage (data: imageData!)!
cell.profileImage.image = image
}
}
}
}
return cell
}
Let me know what you guys think, I want to do make my code much more readable, fast, and memory efficient.
You shouldn't be doing any heavy model stuff inside cellForRow.
What you're currently trying to do will greatly slow down your UI.
In most cases you will want your model objects setup, and ready to go before you even get to cellForRow.
This means performing your Parse queries somewhere like in viewDidLoad, keep those results in an array, and when it comes time to do so, apply them to your cells in cellForRow. This way, when a user scrolls, a new query won't be dispatched for every new cell that comes into view. It will already be available.
In addition to this, should you need to make any changes to these items once they have been fetched, you can do so, and have them remain unchanged even when the user is scrolling.
Refactor so you have some data type or group of instance variables to serve as a view model. Avoid making asynchronous calls that mutate the cell in cellForRowAtIndexPath. Instead have your data access method mutate or recreate the view model and at the end of your callback, dispatch_async to the main queue. Give it a closure that tells your table view to reloadData and whatever else you need to do for views to show the new data.
Here's a little pseudocode to describe what I mean:
func loadData() {
parseQueryWithCallback() { data in
self.viewModel = doWhateverTransformsAreNeeded(data)
dispatch_async(dispatch_get_main_queue(), self.tableView.reloadData)
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) {
let cell = dequeue(...)
cell.thingOne = self.viewModel.things[indexPath.row].thingOne
cell.thingTwo = self.viewModel.things[indexPath.row].thingTwo
return cell
}

Shuffle NSMutableArray with 'Shuffle Albums' for up next queue (MediaPlayer)?

I have managed to create an up next queuing system that works (almost) perfectly. I can move, delete and add songs to the list without any issues at all. The only problem i am having is that when the user decides to use a shuffle mode (e.g. MPMusicShuffleMode.Songs), the up next view still displays the old order (assumes shuffle mode is set to off). The app Ecoute has a similar queuing system but it also works when shuffling.
I've realized that Ecoute does not use the MPMusicShuffleMode, if you go into the stock music player after pressing shuffle in Ecoute, it stays the same. I've figured out a way to display the correct order for shuffled songs (just shuffle the NSMutableArray and set this as the new queue). The real problem is how would i shuffle this array when the user wants to 'Shuffle Albums'? The NSMutableArray contains MPMediaItem if that helps.
Many thanks.
EDIT:
This attempt works but the time grows exponentially for the number of songs. 2000 songs took about 25-35 seconds, so very slow.
else if(self.shuffleMode == "Songs"){
self.shuffleMode = "Albums"
self.shuffle.setTitle("Shuffle Albums", forState: UIControlState.Normal)
var queueCopy = NSMutableArray(array: self.queue.items)
var newQueue = NSMutableArray(array: [])
var albums = MPMediaQuery.albumsQuery().collections as [MPMediaItemCollection]
var albumsCopy = NSMutableArray(array: albums)
shuffleArray(albumsCopy)
for album in albumsCopy{
for item in queueCopy{
if (album.representativeItem!.valueForProperty(MPMediaItemPropertyAlbumTitle) as NSString == item.valueForProperty(MPMediaItemPropertyAlbumTitle) as NSString){
for(var i = 0; i < album.items!.count; i++){
if(album.items![i].valueForProperty(MPMediaItemPropertyTitle) as NSString == item.valueForProperty(MPMediaItemPropertyTitle) as NSString){
newQueue.addObject(item as MPMediaItem)
}
}
}
}
}
let newQueueToSet = MPMediaItemCollection(items: newQueue)
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
appDelegate.currentQueue = newQueueToSet
self.queue = newQueueToSet
self.player.setQueueWithItemCollection(newQueueToSet)
}
EDIT 2:
Managed to get it down to 8 seconds but it's nowhere near Ecoute's 1 to 2 seconds.
8 second version:
var albumNames = [String]()
for item in queueCopy{
albumNames.append(item.valueForProperty(MPMediaItemPropertyAlbumTitle) as NSString)
}
let unique = NSSet(array: albumNames).allObjects as [MPMediaItem]
var uniqueAlbumNames = NSMutableArray(array: unique)
shuffleArray(uniqueAlbumNames)
for name in uniqueAlbumNames{
for item in queueCopy{
if item.valueForProperty(MPMediaItemPropertyAlbumTitle) as NSString == name as NSString{
newQueue.addObject(item as MPMediaItem)
}
}
}
Final Edit:
final piece of code that i'm sticking with. takes about 7-8 seconds for nearly 3000 songs.
#IBAction func shufflePressed(sender: AnyObject) {
if self.shuffleMode == "Off"{
self.shuffleMode = "Songs"
self.shuffle.setTitle("Shuffle All", forState: UIControlState.Normal)
self.shuffle.setTitle("Shuffling", forState: UIControlState.Highlighted)
var queueCopy = NSMutableArray(array: self.queue.items)
self.unshuffledQueueCopy = self.queue
shuffleArray(queueCopy)
let newQueue = MPMediaItemCollection(items: queueCopy)
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
appDelegate.currentQueue = newQueue
self.queue = newQueue
self.player.setQueueWithItemCollection(newQueue)
}
else if(self.shuffleMode == "Songs"){
self.shuffleMode = "Albums"
self.shuffle.setTitle("Shuffle Albums", forState: UIControlState.Normal)
var queueCopy = NSMutableArray(array: self.queue.items)
var newQueue = NSMutableArray(array: [])
var albums = MPMediaQuery.albumsQuery().collections as [MPMediaItemCollection]
var albumsCopy = NSMutableArray(array: albums)
shuffleArray(albumsCopy)
// Takes 8 seconds for 3000 songs
var albumNames = [String]()
for item in queueCopy{
albumNames.append(item.valueForProperty(MPMediaItemPropertyAlbumTitle) as NSString)
}
let unique = NSSet(array: albumNames).allObjects as [MPMediaItem]
var uniqueAlbumNames = NSMutableArray(array: unique)
shuffleArray(uniqueAlbumNames)
for name in uniqueAlbumNames{
for item in queueCopy{
if item.valueForProperty(MPMediaItemPropertyAlbumTitle) as NSString == name as NSString{
newQueue.addObject(item as MPMediaItem)
}
}
}
let newQueueToSet = MPMediaItemCollection(items: newQueue)
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
appDelegate.currentQueue = newQueueToSet
self.queue = newQueueToSet
self.player.setQueueWithItemCollection(newQueueToSet)
}
else if(self.shuffleMode == "Albums"){
self.shuffleMode = "Off"
self.shuffle.setTitle("Shuffle", forState: UIControlState.Normal)
var queueCopy = NSMutableArray(array: self.unshuffledQueueCopy.items)
var nowPlayingItem = self.player.nowPlayingItem
for(var i = 0; i < queueCopy.count; i++){
if(queueCopy[i] as MPMediaItem == nowPlayingItem){
self.fromIndex = i
}
}
let newQueue = MPMediaItemCollection(items: queueCopy)
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
appDelegate.currentQueue = newQueue
self.queue = newQueue
self.player.setQueueWithItemCollection(newQueue)
self.fromItem = newQueue.items[fromIndex + 1] as MPMediaItem
}
So in pseudo code it would look something like the following.
Loop the Array making a new array of the albums only
Shuffle the new Albums array
Loop the new albums array, looking through the original array for items in that album.
On match, write those songs into a third array which will become your new playlist.
Thanks

Resources