OStack程序员社区-中国程序员成长平台

标题: iphone - 将文本/数据以及特殊字符作为参数添加到 iphone 中的 api(url) [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 22:39
标题: iphone - 将文本/数据以及特殊字符作为参数添加到 iphone 中的 api(url)

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

例如:

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];



Best Answer-推荐答案


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 *)urlEncodeUsingEncodingNSStringEncoding)encoding;
@end

@implementation NSString (URLEncoding)
-(NSString *)urlEncodeUsingEncodingNSStringEncoding)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/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4