2017-05-08 83 views
0

我正在從電話庫中選擇歌曲並獲取歌曲路徑的應用程序。我得到歌曲路徑,並希望在Core Data中保存這首歌曲路徑,但我將它保存在Core Data App Crashes中。請提出可能的解決方案。這是我的代碼。保存核心數據應用程序崩潰中的歌曲url路徑

@IBAction func selectMusic(_ sender: Any) { 


    mediaPicker = MPMediaPickerController(mediaTypes: .music) 
    mediaPicker.allowsPickingMultipleItems = true 
    mediaPicker.delegate = self 
    self.present(mediaPicker, animated: true, completion: nil) 
} 



func mediaPicker(_ mediaPicker: MPMediaPickerController, didPickMediaItems mediaItemCollection: MPMediaItemCollection) { 

    self.dismiss(animated: true, completion: nil) 
    let item: MPMediaItem? = (mediaItemCollection.items[0] as? MPMediaItem) 

    print(item) 

    let url: URL? = item?.value(forProperty: MPMediaItemPropertyAssetURL) as! URL? 

    print("My Url : \(url)") 

    var songsUrl : URL = url! 

    let urlString = songsUrl.absoluteString 

    songsUrlArray.append(urlString) 

    print("SONGS ARRAY \(songsUrlArray)") 

    audioPlayer = try! AVAudioPlayer(contentsOf: url!) 
    audioPlayer.play() 
} 

這裏是我保存設置代碼

@IBAction func saveConfiguration(_ sender: Any) { 

    // let email = defaults.value(forKey: "userEmail") 
    let email = "[email protected]" 

    let date = NSDate() 
    var dateFormatter = DateFormatter() 
    dateFormatter.dateFormat = "yyyy-mm-dd" 
    var dateString = dateFormatter.string(from: date as Date) 


    let appDel = UIApplication.shared.delegate as! AppDelegate 

    let context = appDel.persistentContainer.viewContext 

    let newItem = NSEntityDescription.insertNewObject(forEntityName: "Config_Table", into: context) 

    let itemTwo = NSEntityDescription.insertNewObject(forEntityName: "PlayList_Table", into: context) 

    newItem.setValue(email, forKey: "email") 
    newItem.setValue(configurationnameTextField.text, forKey: "config_name") 
    newItem.setValue(selectValueFromPickerView, forKey: "medi_type") 
    newItem.setValue(sliderSelectedValue, forKey: "medi_duration") 
    newItem.setValue(dateString, forKey: "medi_date") 

    itemTwo.setValue(configurationnameTextField.text, forKey: "config_name") 
    itemTwo.setValue(email, forKey: "email") 
    itemTwo.setValue(songsUrlArray, forKey: "song_path") 


    print(newItem) 
    print(itemTwo) 

    do { 
     try context.save() 
     print("Saved") 

    } 
    catch{ 
     fatalError("Error") 

    } 

} 

這裏是我的核心數據結構,其中song_path保存的URL。

enter image description here

這裏是應急信息報告 enter image description here

+0

什麼是崩潰消息?在Simualtor/Device中安裝後是否在CoreData中添加了song_path鍵?如果是,請安裝新的副本或增加型號版本號。 – NeverHopeless

+0

@NeverHopeless請在問題最後看到圖片說明,我不明白你在說什麼。 –

+0

錯誤是明確的。你將你的song_path屬性設置爲一個String,但是當你創建你的實體時,你將放入一個Array中。這就是它崩潰的原因。 – Larme

回答

0

的問題是在這裏:

itemTwo.setValue(songsUrlArray, forKey: "song_path") 

song_path必須是一個NSString。您正在嘗試保存一個數組。