捕获NSLog结果中的值

时间:2014-02-25 21:37:38

标签: ios objective-c nsstring nsmutablestring

编辑以澄清

userID是在服务器端生成的,所以在我发布新注册的用户名和密码之前,我实际上并没有检索到userID。像这样:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSError *error;

NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                        userName.text, @"userName",
                        password.text, @"password",
                        nil];

NSData *data = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];

NSLog(@"PARAMS = %@", params);

[request setHTTPMethod:@"POST"];

[request setValue:@"text/plain" forHTTPHeaderField:@"Accept"];

[request setValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Content-Type"];

[request setHTTPBody:data];

NSURLResponse *response = nil;

NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

NSString *responseString = [[NSString alloc]initWithData:result encoding:NSUTF8StringEncoding];

NSDictionary *json = [NSJSONSerialization JSONObjectWithData:result options:0 error:&error];

NSString *results = json[@"result"];
if ([results isEqualToString:@"ok"])
{
    [self uploadS3Photo];
    NSLog(@"RESULT = %@", responseString);

}

}

编辑结束

我不太确定如何获取值userID,并将其作为NSMutableString发回。

我从数据库中得到的是这个

2014-02-23 20:52:48.029 TestData[245923:92c] RESULT = {"result":"ok","userId":26}

这个数字“26”,我需要存储,然后使用下面的方法回拨它的号码。

-(NSString *)reverseString:(NSString *)str {
    NSMutableString *reversed = [NSMutableString string];
    NSInteger charIndex = [str length];
    while (charIndex > 0) {
        charIndex--;
        NSRange subRange = NSMakeRange(charIndex, 1);
        [reversed appendString:[str substringWithRange:subRange]];
    }
    return reversed;
}

2 个答案:

答案 0 :(得分:3)

您有一个包含JSON内容的字符串。要从中获取数字,您必须使用NSJSONSerialization

以下是如何操作:

NSData *data = [yourJSONString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

NSNumber *myNumber = dict[@"RESULT"][@"userId"];

然后你可以把它转换成字符串:

NSString *stringWithNumber = [myNumber stringValue];

答案 1 :(得分:1)

叹息 -

NSInteger userId = json[@"userId"].integerValue;