2017-04-11 108 views
1

好吧,我在的iMessage應用程序的工作,我試圖從選定的消息這裏 - 我已經成功獲取/在查詢只發送1值解析超過1個網址查詢項目:如何在Swift中傳遞和獲取多個URLQueryItems?

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) 
      } 
     } 

當我只有1價值,只是通過打印conversation.selectedMessage?.url?.query?.description我得到一個可選的1值,這是很好的。但與多個我不能找到一個乾淨的方式來獲得特定的值的關鍵。

對於給定的iMessage鍵,解析URLQueryItem的正確方法是什麼?

回答

3

當你做conversation.selectedMessage?.url?.query?.description它只是打印出查詢的內容。如果你有多個項目,然後它會出現這樣的:

item=Item1&part=Part1&story=Story1 

您可以通過拆分對「&」的字符串,然後分割的「=」,以獲得個人所得陣列的內容,手工解析一個鍵值賦給字典。然後,你可以直接引用的每個值的鍵搞定的具體數值,這樣的事情:

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) 

以上爲您提供了一種簡單的方法通過密鑰來訪問值。但是,這有點冗長。您在代碼中提供的方式,使用queryItems陣列上的過濾器,是更緊湊的解決方案:)因此,您已經擁有了更簡單/緊湊的解決方案,但如果此方法對您個人更有意義,則可以始終使用此路線...

此外,如果問題是您必須多次編寫相同的過濾代碼才能從queryItems數組中獲得值,那麼您始終可以使用一個輔助方法,該方法需要兩個參數:queryItems數組和一個String參數(密鑰),並返回一個可選String值(該值相匹配的鍵)大致如下:

func valueFrom(queryItems:[URLQueryItem], key:String) -> String? { 
    return queryItems.filter({$0.name == key}).first?.value 
} 

然後你上面的代碼看起來像:

if let queryItems = components?.queryItems { 
    // process the query items here... 
    let param1 = valueFrom(queryItems:queryItems, key:"item") 
    print("***************=> GOT IT ", param1) 
} 
0

可以使用iMessageDataKit庫。它使設置和獲取數據非常容易和簡單,如:

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")!) 

(免責聲明:我的iMessageDataKit作者)