Objective-C : NSURL에 쿼리 매개 변수를 추가하는 방법은 무엇입니까?
내가 NSURL
있는가? 이 있는지 여부 이미 빈 쿼리 많은, 내가 어떻게 하나 개 이상의 많은 변수를 추가 수요가 query
의를 NSURL
? 즉,이 기능의 구현을 아는 사람이 있습니까?
- (NSURL *)URLByAppendingQueryString:(NSString *)queryString
따라서 다음 NSURL+AdditionsSpec.h
파일을 무시 합니다.
#import "NSURL+Additions.h"
#import "Kiwi.h"
SPEC_BEGIN(NSURL_AdditionsSpec)
describe(@"NSURL+Additions", ^{
__block NSURL *aURL;
beforeEach(^{
aURL = [[NSURL alloc] initWithString:@"http://www.example.com"];
aURLWithQuery = [[NSURL alloc] initWithString:@"http://www.example.com?key=value"];
});
afterEach(^{
[aURL release];
[aURLWithQuery release];
});
describe(@"-URLByAppendingQueryString:", ^{
it(@"adds to plain URL", ^{
[[[[aURL URLByAppendingQueryString:@"key=value&key2=value2"] query] should]
equal:@"key=value&key2=value2"];
});
it(@"appends to the existing query sting", ^{
[[[[aURLWithQuery URLByAppendingQueryString:@"key2=value2&key3=value3"] query] should]
equal:@"key=value&key2=value2&key3=value3"];
});
});
});
SPEC_END
iOS 7 부터는 사용하기 매우 간단한 NSURLComponents 를 사용할 수 있습니다. 다음 예를 사용합니다.
예 1
NSString *urlString = @"https://mail.google.com/mail/u/0/?shva=1#inbox";
NSURLComponents *components = [[NSURLComponents alloc] initWithString:urlString];
NSLog(@"%@ - %@ - %@ - %@", components.scheme, components.host, components.query, components.fragment);
예 2
NSString *urlString = @"https://mail.google.com/mail/u/0/?shva=1#inbox";
NSURLComponents *components = [[NSURLComponents alloc] initWithString:urlString];
if (components) {
//good URL
} else {
//bad URL
}
예제 3
NSURLComponents *components = [NSURLComponents new];
[components setScheme:@"https"];
[components setHost:@"mail.google.com"];
[components setQuery:@"shva=1"];
[components setFragment:@"inbox"];
[components setPath:@"/mail/u/0/"];
[self.webview loadRequest:[[NSURLRequest alloc] initWithURL:[components URL]]];
그러나 NSURLComponents를 사용하여 다른 많은 작업을 수행 할 수 있습니다. Apple 문서 또는 다음 링크에서 NSURLComponents 클래스 참조를 참조합니다. http://nshipster.com/nsurl/
통과하는 구현은 다음과 사양에 따라 결정됩니다.
@implementation NSURL (Additions)
- (NSURL *)URLByAppendingQueryString:(NSString *)queryString {
if (![queryString length]) {
return self;
}
NSString *URLString = [[NSString alloc] initWithFormat:@"%@%@%@", [self absoluteString],
[self query] ? @"&" : @"?", queryString];
NSURL *theURL = [NSURL URLWithString:URLString];
[URLString release];
return theURL;
}
@end
그리고 여기에 대한 구현이 있습니다 NSString
.
@implementation NSString (Additions)
- (NSURL *)URLByAppendingQueryString:(NSString *)queryString {
if (![queryString length]) {
return [NSURL URLWithString:self];
}
NSString *URLString = [[NSString alloc] initWithFormat:@"%@%@%@", self,
[self rangeOfString:@"?"].length > 0 ? @"&" : @"?", queryString];
NSURL *theURL = [NSURL URLWithString:URLString];
[URLString release];
return theURL;
}
// Or:
- (NSString *)URLStringByAppendingQueryString:(NSString *)queryString {
if (![queryString length]) {
return self;
}
return [NSString stringWithFormat:@"%@%@%@", self,
[self rangeOfString:@"?"].length > 0 ? @"&" : @"?", queryString];
}
@end
iOS8 + 최신 방식
min60.com에있는 URL에 ref = impm 추가 (또는 존재하는 경우 'ref'값 대체)
if ([[url host] hasSuffix:@"min60.com"]) {
NSURLComponents *components = [[NSURLComponents alloc] initWithURL:url resolvingAgainstBaseURL:NO];
NSURLQueryItem * newQueryItem = [[NSURLQueryItem alloc] initWithName:@"ref" value:@"impm"];
NSMutableArray * newQueryItems = [NSMutableArray arrayWithCapacity:[components.queryItems count] + 1];
for (NSURLQueryItem * qi in components.queryItems) {
if (![qi.name isEqual:newQueryItem.name]) {
[newQueryItems addObject:qi];
}
}
[newQueryItems addObject:newQueryItem];
[components setQueryItems:newQueryItems];
url = [components URL];
}
.NET으로 빌드 NSURL
하는 동안 상용구 코드를 작성하고 싶지 않은 사람들을위한 친근한 게시물 입니다 NSURLComponents
.
iOS8 이후로 NSURLQueryItem
URL 요청을 빠르게 구축하는 데 도움이됩니다.
작업을 쉽게하기 위해 약간의 편의를 작성했습니다. 여기에서 얻을 수 있습니다. URLQueryBuilder
다음은 작업이 얼마나 쉬운 지에 대한 예입니다.
NSString *baseURL = @"https://google.com/search";
NSDictionary *items = @{
@"q" : @"arsenkin.com",
@"hl" : @"en_US",
@"lr" : @"lang_en"
};
NSURL *URL = [NSURL ars_queryWithString:baseURL queryElements:items];
// https://google.com/search?q=arsenkin.com&hl=en_US&lr=lang_en
RestKit을 사용하는 경우 NSString에 대한 추가 기능을 제공합니다 . 그중 하나는 다음과 가변적이다.
- (NSString *)stringByAppendingQueryParameters:(NSDictionary *)queryParameters
따라서 다음을 수행 할 수 있습니다.
NSDictionary *shopParams = [NSDictionary dictionaryWithKeysAndObjects:
@"limit",@"20",
@"location",@"latitude,longitude",
nil];
NSString *pathWithQuery = [@"/api/v1/shops.json" stringByAppendingQueryParameters:shopParams]
NSURLComponents
신속하게 추가 쿼리 항목에 대한 확장 이 있습니다.
extension NSURLComponents {
func appendQueryItem(name name: String, value: String) {
var queryItems: [NSURLQueryItem] = self.queryItems ?? [NSURLQueryItem]()
queryItems.append(NSURLQueryItem(name: name, value: value))
self.queryItems = queryItems
}
}
쓰다,
let components = NSURLComponents(string: urlString)!
components.appendQueryItem(name: "key", value: "value")
위의 답변은 NSURLComponents를 언급 한 URL을 처리하는 데 좋은 클래스입니다.
내 대답은 다음과 달라집니다.
NSURL + Additions.h와 같은 NSURL로 카테고리를 만듭니다. 그런 다음 다음 메소드를 추가하고 구현하십시오.
- (NSURL *)URLByAppendingQueryParameters:(NSDictionary *)queryParameters
{
if (queryParameters.count == 0) {
return self;
}
NSArray *queryKeys = [queryParameters allKeys];
NSURLComponents *components = [[NSURLComponents alloc] initWithURL:self resolvingAgainstBaseURL:NO];
NSMutableArray * newQueryItems = [NSMutableArray arrayWithCapacity:1];
for (NSURLQueryItem * item in components.queryItems) {
if (![queryKeys containsObject:item.name]) {
[newQueryItems addObject:item];
}
}
for (NSString *key in queryKeys) {
NSURLQueryItem * newQueryItem = [[NSURLQueryItem alloc] initWithName:key value:queryParameters[key]];
[newQueryItems addObject:newQueryItem];
}
[components setQueryItems:newQueryItems];
return [components URL];
}
NSURL은 변경할 수 없으므로 NSURL을 기반으로이 기능을 직접 구현할 수 없습니다. 대신 URL의 문자열 표현을 가져 와서 여기에 매개 변수를 추가 한 다음 새 NSURL을 만들어야합니다.
이것은 좋은 해결책처럼 들리지 않습니다. 정당한 이유가없는 한, 마지막 순간까지 문자열로 작업하고 완전한 요청이있을 때만 NSURL을 만드는 것이 좋습니다.
참조 URL : https://stackoverflow.com/questions/6309698/objective-c-how-to-add-query-parameter-to-nsurl
'ProgramingTip' 카테고리의 다른 글
Array가 제네릭 유형이 아닌 이유는 무엇입니까? (0) | 2020.12.28 |
---|---|
잠시하는 동안에 평가하는 Xcode (0) | 2020.12.28 |
ssl없이 npm 설치 (0) | 2020.12.28 |
Bash if 문에서 정규식 일치 (0) | 2020.12.28 |
임의의 공유로 string.format (padleft 또는 padright 아님)으로 왼쪽 또는 오른쪽 채우기 (0) | 2020.12.27 |