如何从IOS媒体库中检索元信息

时间:2014-10-26 10:17:27

标签: ios swift

我目前使用此代码将所有信息添加到Media对象中:

for song in songs {
    var media = Media(artist: song.valueForProperty(MPMediaItemPropertyArtist) as String,
                      album: song.valueForProperty(MPMediaItemPropertyAlbumTitle) as String,
                      song: song.valueForProperty(MPMediaItemPropertyTitle) as String,
                      genre: song.valueForProperty(MPMediaItemPropertyGenre) as String,
                      duration: song.valueForProperty(MPMediaItemPropertyPlaybackDuration) as Int,
                      releaseDate: song.valueForProperty(MPMediaItemPropertyReleaseDate) as NSDate,
                      artwork: song.valueForProperty(MPMediaItemPropertyArtwork) as UIImageView,
                      url: song.valueForProperty(MPMediaItemPropertyAssetURL) as NSURL)

    mediaList.append(media)
}

这是init类的Media

    init(artist: String, album: String, song: String, genre: String, duration: Int, releaseDate: NSDate, artwork: UIImageView, url: NSURL) {
............
}

但是我的应用在将对象添加到mediaList之前崩溃了。这是日志:

libswiftCore.dylib`swift_dynamicCastObjCClassUnconditional:
0x328df4:  push   {r4, r7, lr}
0x328df6:  mov    r4, r0
0x328df8:  mov    r2, r1
0x328dfa:  add    r7, sp, #0x4
0x328dfc:  cmp    r4, #0x0
0x328dfe:  beq    0x328e1a                  ; swift_dynamicCastObjCClassUnconditional + 38
0x328e00:  movw   r0, #0x95dc
0x328e04:  movt   r0, #0x1
0x328e08:  add    r0, pc
0x328e0a:  ldr    r1, [r0]
0x328e0c:  mov    r0, r4
0x328e0e:  blx    0x335d94                  ; symbol stub for: objc_msgSend
0x328e12:  tst.w  r0, #0xff
0x328e16:  bne    0x328e1c                  ; swift_dynamicCastObjCClassUnconditional + 40
0x328e18:  trap   
0x328e1a:  movs   r4, #0x0
0x328e1c:  mov    r0, r4
0x328e1e:  pop    {r4, r7, pc}

1 个答案:

答案 0 :(得分:2)

看起来有些值为空,所以我使用了可选链接:

    if let artist = song.valueForProperty(MPMediaItemPropertyArtist) as? String {

    }

    if let album = song.valueForProperty(MPMediaItemPropertyAlbumTitle) as? String {

    }

    if let song = song.valueForProperty(MPMediaItemPropertyTitle) as? String {

    }

    if let gen =  song.valueForProperty(MPMediaItemPropertyGenre) as? String {

    }

    if let duration = song.valueForProperty(MPMediaItemPropertyPlaybackDuration) as? Int {

    }

    if let date = song.valueForProperty(MPMediaItemPropertyReleaseDate) as? NSDate {

    }

    if let img = song.valueForProperty(MPMediaItemPropertyArtwork) as? UIImageView {

    }

    if let url = song.valueForProperty(MPMediaItemPropertyAssetURL) as? NSURL {

    }