ios - 解析 URL 字符串以获取键值的最佳方法?

标签 ios objective-c swift parsing cocoa-touch

我需要像这样解析一个 URL 字符串:

&ad_eurl=http://www.youtube.com/video/4bL4FI1Gz6s&hl=it_IT&iv_logging_level=3&ad_flags=0&endscreen_module=http://s.ytimg.com/yt/swfbin/endscreen-vfl6o3XZn.swf&cid=241&cust_gender=1&avg_rating=4.82280613104

我需要将 NSString 拆分为信号部分,例如 cid=241&avg_rating=4.82280613104。我一直在使用 substringWithRange: 执行此操作,但是这些值以随机顺序返回,因此搞砸了。是否有任何类可以轻松解析,您基本上可以将其转换为 NSDictionary 以便能够读取键的值(例如 ValueForKey:cid 应该返回 241) .还是有比使用 NSMakeRange 获取子字符串更简单的解析方法?

最佳答案

我也在 https://stackoverflow.com/a/26406478/215748 上回答了这个问题.

您可以使用 queryItemsURLComponents.

When you get this property’s value, the NSURLComponents class parses the query string and returns an array of NSURLQueryItem objects, each of which represents a single key-value pair, in the order in which they appear in the original query string.

let url = "http://example.com?param1=value1&param2=param2"
let queryItems = URLComponents(string: url)?.queryItems
let param1 = queryItems?.filter({$0.name == "param1"}).first
print(param1?.value)

或者,您可以在 URL 上添加扩展名以使事情变得更容易。

extension URL {
    var queryParameters: QueryParameters { return QueryParameters(url: self) }
}

class QueryParameters {
    let queryItems: [URLQueryItem]
    init(url: URL?) {
        queryItems = URLComponents(string: url?.absoluteString ?? "")?.queryItems ?? []
        print(queryItems)
    }
    subscript(name: String) -> String? {
        return queryItems.first(where: { $0.name == name })?.value
    }
}

然后您可以通过参数名称访问参数。

let url = URL(string: "http://example.com?param1=value1&param2=param2")!
print(url.queryParameters["param1"])

关于ios - 解析 URL 字符串以获取键值的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8756683/

相关文章:

iOS - 从一台设备向另一台设备流式传输和接收音频以一个仅发送而另一个仅接收结束

ios - 游戏中心排行榜 - 无法将 GKLeaderboardViewController 委托(delegate)设置为自身(CCLayer)

ios - Xcode 13.2.1 : Multiple commands produce problem

iphone - iOS 中的图像圆形环绕

ios - 如何修复警告 : Incompatible pointer types assigning to 'NSMutableString *' from 'NSString *'

ios - 我想将占位符日期显示为当前日期

ios - 使用 UITableViewAutomaticDimension 重新加载 tableview,弹跳

ios - 在iOS上获取软键盘以显示在Pure AS3移动项目中(flex 4.5)

ios - 在不继承 UIControl 的情况下实现目标- Action 模式

ios - 自定义标注 View 不想出现