gpt4 book ai didi

iphone - 在 iphone 中将文本/数据以及特殊字符作为参数添加到 api(url)

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:49:00 24 4
gpt4 key购买 nike

我是 Obj-c 的新手。我正在向 url 添加像文本这样的参数(文本也可能有特殊字符)。但是 url 显示为 nil,它没有从字符串中获取值。

例如:

NSString*strUrl=[NSString stringWithFormat:@"hi how@!#$%^^&*()_=+   r u <>,./ where r u"];

NSString *strMainUrl=[NSString stringWithFormat:@"http://google.com/API/index.php action=listIt&data=%@",strUrl];

NSString *encodeStr = [string stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSURL *url=[NSURL URLWithString:encodeStr];

NSLog(@" url is =%@",url);

但是 url 显示为 nil 值。它没有采用“encodeStr”值。我该如何解决这个问题。请帮助我。

我试过..

NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:str] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30.0];

还有

strEncode=[strEncode stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding];

最佳答案

来自 here 的修改示例:

#import <Foundation/Foundation.h>

// In case you're unfamiliar, this is a category, which allows us to add methods
// to an existing class, even if we didn't create it. It's a nice alternative
// to subclassing.
//
// In this case, we're extending NSString
@interface NSString (URLEncoding)
-(NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding;
@end

@implementation NSString (URLEncoding)
-(NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding {
return (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)self,
NULL,
(CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
CFStringConvertNSStringEncodingToEncoding(encoding));
}
@end

int main(int argc, char *argv[]) {
@autoreleasepool
{
NSString *raw = @"hi how@!#$%^^&*()_=+ r u <>,./ where r u";

// note also, that your string omits the '?' in the URL
NSString *url = [NSString stringWithFormat:@"http://google.com/API/index.php?action=listIt&data=%@",
[raw urlEncodeUsingEncoding:NSUTF8StringEncoding]];

NSURL *finalUrl = [NSURL URLWithString:url];

NSLog(@"%@", finalUrl);
}
}

输出:

http://google.com/API/index.php?action=listIt&data=hi%20how%40%21%23%24%25%5E%5E%26%2A%28%29_%3D%2B%20%20%20r%20u%20%3C%3E%2C.%2F%20where%20r%20u

关于iphone - 在 iphone 中将文本/数据以及特殊字符作为参数添加到 api(url),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12219547/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com