我有一个post方法的字符串。如果string类似于"hello.."
,则值在post方法中传递。但是,如果字符串类似于"hello world"
而不是它没有采用post方法。如果我在字符串中使用空格,它就不起作用了。请帮帮我。
- (void) constructURL
{
NSMutableString* curl = [[NSMutableString alloc] init];
[curl appendString:@"XXXXX"];
[curl appendString:[NSString stringWithFormat:@"?eventid=%@", eventID]];
[curl appendString:[NSString stringWithFormat:@"&ForumID=%@", forumID]];
[curl appendString:[NSString stringWithFormat:@"&parentPostID=%@", parentPostID]];
[curl appendString:[NSString stringWithFormat:@"&userid=%@", userID]];
[curl appendString:[NSString stringWithFormat:@"&PostContent=%@", postContent]];
url = [NSURL URLWithString:curl];
}
答案 0 :(得分:1)
我认为您需要像这样对字符串进行编码:
NSString* encodedString = [@"Hello World" stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
答案 1 :(得分:0)
阅读这些内容,可能对您有所帮助。摘自苹果文档https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/
Working with URLs
stringByAddingPercentEscapesUsingEncoding:
Returns a representation of the receiver using a given encoding to determine the percent escapes necessary to convert the receiver into a legal URL string.
Declaration
SWIFT
func stringByAddingPercentEscapesUsingEncoding(_ encoding: UInt) -> String?
OBJECTIVE-C
- (NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
Parameters
encoding
The encoding to use for the returned string. If you are uncertain of the correct encoding you should use NSUTF8StringEncoding.
Return Value
A representation of the receiver using encoding to determine the percent escapes necessary to convert the receiver into a legal URL string. Returns nil if encoding cannot encode a particular character.
Discussion
It may be difficult to use this function to "clean up" unescaped or partially escaped URL strings where sequences are unpredictable. See CFURLCreateStringByAddingPercentEscapes for more information.
Import Statement
import Foundation
Availability
Available in OS X v10.3 and later.
See Also
– stringByAddingPercentEncodingWithAllowedCharacters:
– stringByReplacingPercentEscapesUsingEncoding:
– stringByRemovingPercentEncoding
你的问题答案是:
- (void) constructURL
{
NSMutableString* curl = [[NSMutableString alloc] init];
[curl appendString:@"XXXXX"];
[curl appendString:[NSString stringWithFormat:@"?eventid=%@", eventID]];
[curl appendString:[NSString stringWithFormat:@"&ForumID=%@", forumID]];
[curl appendString:[NSString stringWithFormat:@"&parentPostID=%@", parentPostID]];
[curl appendString:[NSString stringWithFormat:@"&userid=%@", userID]];
[curl appendString:[NSString stringWithFormat:@"&PostContent=%@", postContent]];
curl = [curl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
url = [NSURL URLWithString:curl];
}