2016-09-20 53 views
4

因此,我正在搞亂iMessages框架,並且爲了向其他用戶發送數據,必須將數據作爲URLComponentsURL發送。但我不知道如何發送一個字典作爲messages.url值使用。如何通過在Swift中使用字典來構建URL

func createMessage(data: dictionary) { 

    /* 

    The Dictionary has 3 values, 1 string and two arrays. 

    let dictionary = ["title" : "Title Of Dictionary", "Array1" : [String](), "Array2" : [String]() ] as [String : Any] 

    */ 


    let components = URLComponents() 

    let layout = MSMessageTemplateLayout() 
    layout.image = UIImage(named: "messages-layout.png")! 
    layout.imageTitle = "\(dictionary["title"])" 

    let message = MSMessage() 
    message.url = components.url! 
    message.layout = layout 

    self.activeConversation?.insert(message, completionHandler: { (error: Error?) in 
     print("Insert Message") 
    }) 
} 

有誰知道我可以在URLComponents送字典值URLQueryItems保存爲message.url? PS:我想知道是否有可能爲存儲字典的URL創建擴展名,這是我嘗試atm失敗的原因。

回答

7

下面的代碼片段轉換字典URLQueryItems

let dictionary = [ 
    "name": "Alice", 
    "age": "13" 
] 

func queryItems(dictionary: [String:String]) -> [URLQueryItem] { 
    return dictionary.map { 
     // Swift 3 
     // URLQueryItem(name: $0, value: $1) 

     // Swift 4 
     URLQueryItem(name: $0.0, value: $0.1) 
    } 
} 

var components = URLComponents() 
components.queryItems = queryItems(dictionary: dictionary) 
print(components.url!) 
+0

斯威夫特4更新: 'FUNC queryItems(詞典:[字符串:String]) - > [URLQueryItem] { return dictionary.map { URLQueryItem(name:$ 0.0,value:$ 0.1) } }' – palme

+0

@palme thanks。我已經用你的代碼片段更新了代碼。 –

1

您可以使用以下URLComponents擴展:

extension URLComponents{ 
    var queryItemsDictionary : [String:Any]{ 
     set (queryItemsDictionary){ 
      self.queryItems = queryItemsDictionary.map { 
       URLQueryItem(name: $0, value: "\($1)") 
      } 
     } 
     get{ 
      var params = [String: Any]() 
      return queryItems?.reduce([:], { (_, item) -> [String: Any] in 
       params[item.name] = item.value 
       return params 
      }) ?? [:] 
     } 
    } 
} 

,並設置URL組件:

var url = URLComponents() 
url.queryItemsDictionary = ["firstName" : "John", 
          "lastName" : "Appleseed"] 
0

您可以使用iMessageDataKit庫。這是一個微小的,有用的MSMessage擴展名,用於設置/獲取Int,Bool,Float,Double,StringArray鍵的值。

它使設置和獲取數據非常簡單,如:

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作者)

相關問題