How to extract a value from [DDXMLElement] in Swift? - swift

I want to extract the value of id in the stanza tag.
The stanza tag is:
[<stanza-id xmlns="urn:xmpp:sid:0" by="f.talebi#wepod.ir" id="1531235744929009"></stanza-id>]
This is a part of message received from Xmpp server. I need to extract "1531235744929009" value. Therefore, I wrote this:
var stanza = message.elements(forName: "stanza-id")
print(stanza)
var id = stanza.first?.attributes
if let attributes = stanza.first?.attributes {
let lastItem = attributes.last
if let stanzaID = lastItem?.stringValue {
print("stanzaID = \(stanzaID)")
}
}
This code works correctly, but its not a clean code. especially where I wrote this line lastItem = attributes.last because if the order changes this won't work.

just use stanza.attributed(forName: String)

Related

ITunes Library Framework in Swift 5.2

I have searched everywhere and I am unable to find a swifty example of how to use the Apple ITunesLibraryFramework. I have been trying to figure out how to use this Framework in Swift 5.2.
I want to get information directly from the Music library rather than having to rely on a XML library export file.
I have the below code in my playground and it prints nothing legible. How would I access the fields for playlists and mediaItems and be able to read them in human readable form?
I have installed the framework in the project. This is my project playground code:
import Foundation
import iTunesLibrary
var library:ITLibrary
do {
let library = try ITLibrary(apiVersion: "1.1")
let mediaItems = library.allMediaItems
let playlists = library.allPlaylists
print("Media Folder Location - \(String(describing: library.mediaFolderLocation))")
print("\nPlaylists - \(playlists)")
print("\nTracks - \(mediaItems)")
} catch let error as NSError {
print(error)
}
This is the ITLibrary.m file that I imported the header:
#import <Foundation/Foundation.h>
#import <iTunesLibrary/iTunesLibrary.h>
When I run the above code in the project playground all I get is a bunch of binary data for both playlists and mediaItems. All I want to do is iterate over the data and collect information from the library for use in my program. It's probably something easy, but I haven't found it yet.
EDIT: - After using #Vincent's answer I ran into another problem with the following code:
import Foundation
import iTunesLibrary
let library = try ITLibrary(apiVersion: "1.1")
typealias tracks = [NSNumber:TrackInfo]
var trackInfo = TrackInfo()
struct TrackInfo {
var title = ""
var artist = ""
var album = ""
var totalTime = 0
var year = 0
var persistentID = ""
var location:URL!
}
let songs = library.allMediaItems
let playlists = library.allPlaylists
for playlist in playlists {
if playlist.name.lowercased().contains("test-") {
print("New Playlist---------------\nName: \(playlist.name)")
for song in playlist.items {
trackInfo.title = song.title
print("\n\nNew Track-----------------\nTitle: \(trackInfo.title)")
if song.artist?.name != nil {
trackInfo.artist = song.artist?.name as! String
}
print("Artist: \(trackInfo.artist)")
trackInfo.album = song.album.title!
print("Albumn Name: \(trackInfo.album)")
trackInfo.totalTime = song.totalTime
print("Total Time: \(trackInfo.totalTime)")
trackInfo.year = song.year
print("Year: \(trackInfo.year)")
trackInfo.location = song.location!
print("Location: \(trackInfo.location!)")
var persistentID = song.persistentID
tracks.updateValue(song.persistentID, trackInfo)
}
}
}
The issue I'm having is getting the tracks info into the trackInfo dictionary. I'm trying to use the track persistentID (NSNumber) as the key for the dictionary, which I have declared. For some reason it isn't allowing me to use it.
Here's how you can have it print each playlist and track:
Each ITLibPlaylist or ITLibMediaItem object contains many information about each playlist/media item. To get only the name/title of each, you will have to iterate through the results to retrieve them.
For this example below, the name of each playlist's name is printed.
print("\nPlaylists -")
for playlist in playlists {
print(playlist.name)
}
Which will print (for example):
Playlists -
Library
Music
For this example below, the name of each track's name is printed.
print("\nTracks -")
for mediaItem in mediaItems {
print(mediaItem.title)
}
Which will print (for example):
Tracks -
Ev'ry Time We Say Goodbye
My Favorite Things
But Not for Me
Summertime
Edit: Here's the secondary solution to the secondary problem:
First things first, a dictionary should be initialised, instead of using typealias.
typealias only makes an alias for a pre existing type, like
typealias NumberWithAlotOfDecimals = Double
let a: NumberWithAlotOfDecimals = 10.1
let b: Double = 10.1
both will a and b are Double, as NumberWithAlotOfDecimals is just an alias for Double.
Here's how to initialise:
//typealias tracks = [NSNumber:TrackInfo] // not this
var tracks = [NSNumber:TrackInfo]() // but this
Secondly, nullable objects should be properly handled
if let artistName = song.artist?.name {
trackInfo.artist = artistName
}
and
if let title = song.album.title {
trackInfo.album = title
}
if let location = song.location {
trackInfo.location = location
print("Location: \(location)")
}
instead of
if song.artist?.name != nil {
trackInfo.artist = song.artist?.name as! String
}
Please do not use ! to force unwrap nullable objects as that will cause runtime crashes when the object is nil.
Lastly, this is the way to store key value into dictionary in Swift.
let persistentID = song.persistentID
//tracks.updateValue(song.persistentID, trackInfo) // not this
tracks[persistentID] = trackInfo // this

want to update data after editing

i want to update data after editing. for that i need the previous data.
but in my case after editing, the variable that hold the previous value are replaced by the present value.
how can i hold the previous value??
if itemToEdit == nil{
item = TestDataModel()
else{
item = itemToEdit
selectedItemToEdit = itemToEdit
// print(selectedItemToEdit?.title)
print(item.title)
// print(itemToEdit?.title)
}
if let title = titleField.text {
item.title = title
print(item.title)
}
// print(selectedItemToEdit.title!)
print(itemToEdit?.title!)
if let price = pricefield.text {
item.price = (price as NSString).doubleValue
print(item.price)
}
if let details = detailsField.text {
item.details = details
print(item.details)
}
itemToEdit, is that which i want to edit/ update. that's why i stored it in selectedItemToEdit. in item, i have stored the data after editing.
i need both the previous value and the present value that i entered in textfield.
how can i get that one.please any one help....
What you're doing when you try to save previous information is simply creating a new variable that points to the same object. When the object changes, it doesn't matter what variable you use to examine it, you will see the changes in that one object.
Here's a playground sample that should give you an idea of the difference between having two objects vs. having two pointers to the same object.
class MyData {
var title = "Default"
init() {
}
init(source: MyData)
{
title = source.title
}
}
var d1 = MyData()
var d2 = d1
var d3 = MyData(source: d1)
d1.title = "changed"
print(d2.title)
print(d3.title)
yeah i solved the problem:
i just declared a variable of string type as bellow:
var selectedItemToEdit: string!
selectedItemToEdit = itemToEdit.title
i passed that string type variable and the edited variable to the save function.

Swift `reversed()` not ordering how I thought it would

Why would this produce Elena instead of Paula?
let names = ["Paula", "Elena", "Zoe"]
var lastNameEndingInA: String?
for name in names.reversed() where name.hasSuffix("a") {
lastNameEndingInA = name
break
}
lastNameEndingInA // Optional("Elena")”
I would have thought that names.reversed() would be [“Zoe”, “Paula”, “Elena”] and then where name.hasSuffix(“a”) would skip “Zoe” and then go to “Paula” then break so lastNameEndingInA would be “Paula”?
I can’t figure out why it isn’t working like that though.
Your array is ["Paula", "Elena", "Zoe"]. When reversed it is ["Zoe", "Elena", "Paula"]. There is no reason to think it would be [“Zoe”, “Paula”, “Elena”]. So your code is working as expected.
But it can be written more easily as:
let lastNameEndingInA = names.reversed().first { $0.hasSuffix("a") }
It you want the names sorted in reverse and then find the match, do:
let lastNameEndingInA = names.sorted().reversed().first { $0.hasSuffix("a") }

How to identify the type of an object?

Here is my JSON response for a particular API.
Case 1
ChallengeConfiguration = {
AnswerAttemptsAllowed = 0;
ApplicantChallengeId = 872934636;
ApplicantId = 30320480;
CorrectAnswersNeeded = 0;
MultiChoiceQuestion = (
{
FullQuestionText = "From the following list, select one of your current or previous employers.";
QuestionId = 35666244;
SequenceNumber = 1;
},
{
FullQuestionText = "What color is/was your 2010 Pontiac Grand Prix?";
QuestionId = 35666246;
SequenceNumber = 2;
}
)
}
The key "MultiChoiceQuestion" returns an array with two questions. So here is my code.
let QuestionArray:NSArray = dict1.objectForKey("ChallengeConfiguration")?.objectForKey("MultiChoiceQuestion") as! NSArray
Case 2
ChallengeConfiguration =
{
AnswerAttemptsAllowed = 0;
ApplicantChallengeId = 872934636;
ApplicantId = 30320480;
CorrectAnswersNeeded = 0;
MultiChoiceQuestion = {
FullQuestionText = "From the following list, select one of your
current or previous employers.";
QuestionId = 35666244;
SequenceNumber = 1;
}
}
For Case 2 my code does not work and app crashes because it returns a dictionary for that specific Key. So how could I write a generic code that would work for all objects?
It looks like the key can contain either an array of dictionary values or a dictionary, so you just need to try casting to see which one you have.
so I would likely do it like this:
if let arr = dict1.objectForKey("ChallengeConfiguration")?.objectForKey("MultiChoiceQuestion") as? Array {
// parse multiple items as an array
} else if let arr = dict1.objectForKey("ChallengeConfiguration")?.objectForKey("MultiChoiceQuestion") as? [String:AnyObject] {
// parse single item from dictionary
}
You should never really use ! to force unwrap something unless you are completely certain that the value exists and is of the type you are expecting.
Use conditional logic here to test the response and parse it safely so that your app doesn't crash, even in failure.

How to pass and get multiple URLQueryItems in Swift?

Ok, I am working in an iMessage app and am trying to parse more than 1 url query item from the selected message here- I have been successful getting/sending just 1 value in a query:
override func willBecomeActive(with conversation: MSConversation) {
// Called when the extension is about to move from the inactive to active state.
// This will happen when the extension is about to present UI.
if(conversation.selectedMessage?.url != nil) //trying to catch error
{
let components = URLComponents(string: (conversation.selectedMessage?.url?.query?.description)!)
//let val = conversation.selectedMessage?.url?.query?.description
if let queryItems = components?.queryItems {
// process the query items here...
let param1 = queryItems.filter({$0.name == "theirScore"}).first
print("***************=> GOT IT ",param1?.value)
}
}
When I just have 1 value, just by printing conversation.selectedMessage?.url?.query?.description I get an optional with that 1 value, which is good. But with multiple I cant find a clean way to get specific values by key.
What is the correct way to parse a URLQueryItem for given keys for iMessage?
When you do conversation.selectedMessage?.url?.query?.description it simply prints out the contents of the query. If you have multiple items then it would appear something like:
item=Item1&part=Part1&story=Story1
You can parse that one manually by splitting the string on "&" and then splitting the contents of the resulting array on "=" to get the individual key value pairs in to a dictionary. Then, you can directly refer to each value by key to get the specific values, something like this:
var dic = [String:String]()
if let txt = url?.query {
let arr = txt.components(separatedBy:"&")
for item in arr {
let arr2 = item.components(separatedBy:"=")
let key = arr2[0]
let val = arr2[1]
dic[key] = val
}
}
print(dic)
The above gives you an easy way to access the values by key. However, that is a bit more verbose. The way you provided in your code, using a filter on the queryItems array, is the more compact solution :) So you already have the easier/compact solution, but if this approach makes better sense to you personally, you can always go this route ...
Also, if the issue is that you have to write the same filtering code multiple times to get a value from the queryItems array, then you can always have a helper method which takes two parameters, the queryItems array and a String parameter (the key) and returns an optional String value (the value matching the key) along the following lines:
func valueFrom(queryItems:[URLQueryItem], key:String) -> String? {
return queryItems.filter({$0.name == key}).first?.value
}
Then your above code would look like:
if let queryItems = components?.queryItems {
// process the query items here...
let param1 = valueFrom(queryItems:queryItems, key:"item")
print("***************=> GOT IT ", param1)
}
You can use iMessageDataKit library. It makes setting and getting data really easy and straightforward like:
let message: MSMessage = MSMessage()
message.md.set(value: 7, forKey: "user_id")
message.md.set(value: "john", forKey: "username")
message.md.set(values: ["joy", "smile"], forKey: "tags")
print(message.md.integer(forKey: "user_id")!)
print(message.md.string(forKey: "username")!)
print(message.md.values(forKey: "tags")!)
(Disclaimer: I'm the author of iMessageDataKit)