2

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

4

1 回答 1

4

从这里修改的例子:

#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
于 2012-08-31T17:03:24.083 回答