__NSCFNumber stringByAddingPercentEncodingWithAllowedCharacters无法识别的选择器错误

时间:2017-03-16 19:21:51

标签: ios objective-c

所以我是使用Objective-c进行编程的新手。我想用HTTP POST方法发出请求。我发送的参数是int类型。

我收到了这个错误:

[__NSCFNumber stringByAddingPercentEncodingWithAllowedCharacters:]: unrecognized selector sent to instance 0xb0000000000048d3

在这行代码中:

return [string stringByAddingPercentEncodingWithAllowedCharacters:allowed];

整个守则:

 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
request.HTTPMethod = @"POST";
[request setHTTPBody:[self httpBodyForParameters:params]];

NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if (error) {
        NSLog(@"dataTaskWithRequest error: %@", error);
    }
    if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
        NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
        if (statusCode != 200) {
            NSLog(@"Expected responseCode == 200; received %ld", (long)statusCode);
        }}
    NSError *parseError;
    id responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
     if (!responseObject) {
        NSLog(@"JSON parse error: %@", parseError);
    } else {
    NSLog(@"responseObject = %@", responseObject);
     }
    NSLog(@"print123");

}];
[task resume];
}

- (NSData *)httpBodyForParameters:(NSDictionary *)parameters {
NSMutableArray *parameterArray = [NSMutableArray array];
    [parameters enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL *stop) {
NSString *param = [NSString stringWithFormat:@"%@=%@", [self percentEscapeString:key], [self percentEscapeString:obj]];
    [parameterArray addObject:param];
}];

NSString *string = [parameterArray componentsJoinedByString:@"&"];

    return [string dataUsingEncoding:NSUTF8StringEncoding];
}

- (NSString *)percentEscapeString:(NSString *)string {
NSCharacterSet *allowed = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"];
return [string stringByAddingPercentEncodingWithAllowedCharacters:allowed];
}

1 个答案:

答案 0 :(得分:1)

@ Paulw11是正确的,错误是数字被视为字符串的结果。一个立即(但有点笨重)的修复是对枚举字典时找到的值类型的更少承诺......

// notice we change the type of obj id, not NSString*
[parameters enumerateKeysAndObjectsUsingBlock:^(NSString *key, id obj, BOOL *stop) {
    // now, test for it's type and treat accordingly
    NSString *objString = ([obj isKindOfClass:[NSString self]])? [self percentEscapeString:obj] : [obj stringValue];
    NSString *param = [NSString stringWithFormat:@"%@=%@", [self percentEscapeString:key], objString];
    [parameterArray addObject:param];
}];

但是这个脆弱的解决方案现在只适用于字符串和数字。如果你可以说服服务器接受JSON,那么请求代码可以像这样简化和generalized ......

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
request.HTTPMethod = @"POST";

// params is your original (serializable) dictionary
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject: params options:0 error:&error];
[request setHTTPBody:postData];

NSURLSessionTask *task =  // ...