簡體   English   中英

如何從NSString獲取值

[英]How to get Values from a NSString

我有一個NSString 這是使用通用鏈接時獲得的URL。 我想從中獲取ID值。 SDK中是否有任何直接方法,還是我們需要使用componententsSeparated String值?

以下是NSString / URL:

https://some.com/cc/test.html?id=3039#value=test

我想得到兩件事:來自test.html的“測試”和“ id”值。

使用從您的URL的NSURLNSString創建的NSURLComponents

從那里可以使用path獲得/cc/test.html部分。 然后使用lastPathComponent獲取test.html ,最后使用stringByDeletingPathExtension獲取test

要獲取“ id”值,請從組件的queryItems值開始。 迭代該數組,找到名稱為“ id”的NSURLQueryItem ,然后獲取其值。

您可以通過調用queryItems方法從URL字符串get參數創建NSURLComponents 它將返回NSURLQueryItem數組

NSURLComponents *components = [NSURLComponents componentsWithString:@"https://some.com/cc/test.html?id=3039&value=test"];
    NSArray *array = [components queryItems];
    for(NSURLQueryItem *item in array){
        NSLog(@"Name: %@, Value: %@", item.name, item.value);
    }
    NSLog(@"Items: %@", array);

我們可以擴展

  extension URL {              
      func getParamValue(paramaterName: String) -> String? {
          guard let url = URLComponents(string:self.absoluteString ) else { return nil }
             return url.queryItems?.first(where: { $0.name == paramaterName})?.value
      }
  }

現在您可以像下面這樣打電話

let someURL = URL(string: "https://some.com/cc/test.html?id=3039&value=test")!
someURL.getParamValue("id") // 3039
someURL.getParamValue("value") // test

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM