将URL链接解析为段

时间:2016-06-06 12:24:42

标签: ios nsstring nsurl

http://180.160.1.140/webapp/camera?id=fksmf84-8493-45u3

如何获取此网址部分fksmf84-8493-45u3 ?? - 这部分在运行时间不断变化。

这是我到目前为止所尝试过的。

NSString *url = @"http://180.160.1.140/webapp/camera?id=";
NSArray *parts = [url componentsSeparatedByString:@"="];
NSString *personID = [parts lastObject];
NSLog(@"My ID: %@", personID);

3 个答案:

答案 0 :(得分:5)

使用网址组件:

ObjC:

NSString *urlString = "http://180.160.1.140/webapp/camera?id=fksmf84-8493-45u3";
NSURLComponents *components = [NSURLComponents componentsWithString:urlString];
NSArray *queryItems = components.queryItems;

for (NSURLQueryItem *queryItem in queryItems) {
    if ([queryItem.name isEqualToString:@"id"]) {
        NSLog(@"%@", queryItem.value);
        break;
    }
}

夫特:

let urlComponents = NSURLComponents(string: "http://180.160.1.140/webapp/camera?id=fksmf84-8493-45u3")
let queryItems = urlComponents?.queryItems
if let id = queryItems?.filter({$0.name == "id"}).first?.value {
    print(id)
}

Swift 3(基本相同 - NS):

let urlComponents = URLComponents(string: "http://180.160.1.140/webapp/camera?
id=fksmf84-8493-45u3")
let queryItems = urlComponents?.queryItems
if let id = queryItems?.filter({$0.name == "id"}).first?.value {
    print(id)
}

答案 1 :(得分:3)

要解析所有键值对并将其作为词典,您可以使用-parseQueryString:方法。

您可以像这样解析查询字符串......

   {
    //...
    NSString * urlQuery              = [url query];
    NSDictionary *dict = [self parseQueryString:urlQuery];
    NSString * valueForID = dict["id"];
    //...
    }
    // Waring : Its just a prototype, at production this might need safety checks.
    - (NSDictionary *)parseQueryString:(NSString *)query
    {
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
        NSArray *pairs = [query componentsSeparatedByString:@"&"];

        for (NSString *pair in pairs)
        {
            NSArray *elements = [pair componentsSeparatedByString:@"="];
            NSString *key = [[elements objectAtIndex:0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSString *val = [[elements objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

            [dict addObject:val forKey:key];
        }
        return dict;
    }

更新:如果定位的iOS版本低于7,请查看Richmond Watkins的答案。为了同样的目的添加了新的api,检查NSURLQueryItem

答案 2 :(得分:0)

请参阅:

NSString *url = @"http://180.160.1.140/webapp/camera?id=fksmf84-8493-45u3"; // you forgot to add the id in your test case
NSArray *parts = [url componentsSeparatedByString:@"="];
NSString *personID = [parts lastObject];
NSLog(@"My ID: %@", personID);

输出:我的ID:fksmf84-8493-45u3

修改

存储数据:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

[defaults setObject:personID forKey:@"personID"];

阅读数据:

 NSString *personID = [defaults objectForKey:@"personID"];

使用此方法,您可以轻松获取上次运行的值。希望这会对你有帮助:)。