1

我的问题是在 iOS7 上采用[NSURLConnection sendAsynchronousRequest...]withPOST方法失败,但在 iOS6 环境下成功。

其他信息:

  1. 在我的 iOS6 环境中可以像这样从服务器获取 JSON 数据。(成功的)

    {
        "status": 200,
        "data": [
            {
                "oauth_token": "BVgOa01tg6JvfuXOPoJS8wB26TpvAaDs"
            }
        ]
    }
    
  2. iOS7 上的相同代码将收到此错误消息。(失败的)

    错误:错误域=NSCocoaErrorDomain 代码=3840“操作无法完成。(可可错误 3840。)”(无值。)

  3. 我检查了服务器端的 PHP 代码,发现服务器可以从 iOS6 POST 数据中获取数据,但无法从 iOS7 获取 POST 数据。(相同的代码不同的结果,很奇怪。)

有没有人可以帮助我或为我提供建议?多谢。

我的代码如下(更新到 v3,成功)(感谢 Rob 的回答)

- (void) apiLogin
{
    NSDictionary *params = @{@"client_id"     : @"1234567",
                         @"response_type" : @"token",
                         @"redirect_uri"  : @"/oauth2-php/server/examples/pdo/",
                         @"state"         : @"test_state",
                         @"scope"         : @"",
                         @"accept"        : @"Yep",
                         @"uid"           : uid,
                         @"pwd"           : withPwd};

    NSData *postDataString = [self dataForHTTPPost:params];

    // Server API 位置
    NSURL *url=[NSURL URLWithString:@"http://xxx.xxx.tw/xxx.php"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:120];
    [request setURL:url];

    // Solution3:
    NSString *postLength = [NSString stringWithFormat:@"%d", [postDataString length]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postDataString];

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

        NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
        NSLog(@"D1: responseCode: %d", responseCode);
        if (!connectionError && responseCode == 200) {
            // 採用Apple官方方法將 來源轉成JSON Format並交由NSDictionary 接手.
            NSError *localError = nil;
            NSLog(@"data:%@", data);
            NSDictionary *allInDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&localError];
            NSLog(@"Source:%@", allInDic);
            NSLog(@"error:%@", localError);

            // 取出oauth_token資料
            if ([[allInDic objectForKey:@"status"] integerValue] == 200) {

                // 將新取得之 oauth_token 寫入DB
                NSArray * dataArray = [allInDic objectForKey:@"data"];
                NSDictionary *responseData = [dataArray objectAtIndex:0];

                NSString *t = [responseData objectForKey:@"oauth_token"];
                [helper setDbOauthToken:nil :t :TABLE_USER_PROFILES];
                NSLog(@"(API-New)oauth_token:%@", t);
            } else
            {
              NSLog(@"connectionError=%@", connectionError);
              NSLog(@"responseCode=%d", responseCode);
            }
        }
    }];
}

- (NSData *)dataForHTTPPost:(NSDictionary*) parms
{
    NSMutableArray *array = [NSMutableArray array];
    for (NSString *key in parms) {
        id obj = [parms objectForKey:key];
        NSString *valueString;

        if ([obj isKindOfClass:[NSString class]])
          valueString = obj;
        else if ([obj isKindOfClass:[NSNumber class]])
          valueString = [(NSNumber *)obj stringValue];
        else if ([obj isKindOfClass:[NSURL class]])
          valueString = [(NSURL *)obj absoluteString];
        else
          valueString = [obj description];

        [array addObject:[NSString stringWithFormat:@"%@=%@", key, valueString]];
    }
    NSString *postString = [array componentsJoinedByString:@"&"];
    NSLog(@"New2a HTTPPost Data:%@", postString);

    return [postString dataUsingEncoding:NSUTF8StringEncoding];
}

- (IBAction)loginAction:(id)sender {

    [self apiLogin];
}

下面的代码是 iOS6 上的调试输出

New2a HTTPPost Data:response_type=token&uid=xxx&accept=Yep&scope=&client_id=1234567&state=test_state&redirect_uri=/oauth2-php/server/examples/pdo/&pwd=xxx
D1: responseCode: 200
data:<7b227374 61747573 223a3230 302c2264 61746122 3a5b7b22 6f617574 685f746f 6b656e22 3a224870 47366546 4b304a37 38434343 54306352 506e4d77 62544d5c 2f455631 32793422 7d5d7d>
Source:{
    data =     (
                {
            "oauth_token" = "HpG6eFK0J78CCCT0cRPnMwbTM/EV12y4";
        }
    );
    status = 200;
}
error:(null)
(API-New)oauth_token:HpG6eFK0J78CCCT0cRPnMwbTM/EV12y4

下面的代码是 iOS7 上的调试输出

New2a HTTPPost Data:response_type=token&uid=&accept=Yep&scope=&client_id=1234567&state=test_state&redirect_uri=/oauth2-php/server/examples/pdo/&pwd=
D1: responseCode: 200
data:<>
Source:(null)
error:Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (No value.) UserInfo=0x8a28d90 {NSDebugDescription=No value.}
connectionError=(null)
responseCode=200

感谢 Rob 的大力帮助,我的问题已解决。根课程在代码下方。在 IOS6 中,当“idField.txt”字段没有输入时,我可以获得 uid/withPwd 默认值。但在 iOS7 中,此代码无法使用 (uid/withPwd) 获取默认值。感谢 Rob,我的问题已解决。

NSString *uid = idField.text;
NSString *withPwd = pwdField.text;

// For testing Account ID
if (!uid||!withPwd) {
    uid=@"xxx@gmail.com";
    withPwd=@"xxxx";
}
NSLog(@"uid:%@ , pwd:%@", uid, withPwd);

将问题代码更新为适用于 iOS6 和 iOS7

// For testing Account ID
if ([uid isEqualToString:@""] || [withPwd isEqualToString:@""] ) {
    uid=@"xxx@gmail.com";
    withPwd=@"xxxx";
}
4

2 回答 2

2

您正在记录data,但您可能想查看它的字符串表示形式。查看生成的字符串并查看服务器响应中的内容。这样,如果您的服务器失败并返回了一些非 JSON 错误消息,您可以看到字符串是什么。

同样,您可能想要记录connectionErrorif it's not nil。这不是这里的情况(否则,你不会得到你的 current NSLog,但如果不是的话,可能值得看看nil)。因此:

if (!connectionError && responseCode == 200) {
    // 採用Apple官方方法將 來源轉成JSON Format並交由NSDictionary 接手.
    if (data)
        NSLog(@"data string: %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    else
        NSLog(@"data is nil");

    NSError *parseError = nil;
    NSDictionary *allInDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&parseError];
    NSLog(@"Source:%@", allInDic);
    NSLog(@"error:%@", parseError);

    // 取出oauth_token資料
    if ([allInDic[@"status"] integerValue] == 200) {

        // 將新取得之 oauth_token 寫入DB
        NSArray * dataArray = allInDic[@"data"];
        NSDictionary *responseDictionary = dataArray[0];

        NSString *t = responseDictionary[@"oauth_token"];
        [helper setDbOauthToken:nil :t :TABLE_USER_PROFILES];
        NSLog(@"(API-New)oauth_token:%@", t);
    }
}
else
{
    NSLog(@"connectionError=%@", connectionError);
    NSLog(@"responseCode=%d", responseCode);
}

我怀疑,一旦您查看 的字符串表示形式data,问题可能会变得不言而喻。


顺便说一句,这不太可能是问题,但请确保您正确编码了要添加到postData. 例如,如果您的密码包含与号、加号、空格或其他一些保留字符(如RFC2396的第 2.2 节中所述),您当前的代码将不起作用。您可能希望应用CFURLCreateStringByAddingPercentEscapes到您添加到您的值postData,例如,您可以使用NSString这样的类别:

@implementation NSString (URLPostEncode)

- (NSString *)stringForHTTPPost
{
    NSString *result = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                                 (CFStringRef)self,
                                                                                 (CFStringRef)@" ",
                                                                                 (CFStringRef)@";/?:@&=+$,",
                                                                                 kCFStringEncodingUTF8));
    return [result stringByReplacingOccurrencesOfString:@" " withString:@"+"];
}

@end

我个人将其与以下NSDictionary类别结合起来:

@implementation NSDictionary (URLPostEncode)

- (NSData *)dataForHTTPPost
{
    NSMutableArray *array = [NSMutableArray array];
    [self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        NSString *valueString;

        if ([obj isKindOfClass:[NSString class]])
            valueString = obj;
        else if ([obj isKindOfClass:[NSNumber class]])
            valueString = [(NSNumber *)obj stringValue];
        else if ([obj isKindOfClass:[NSURL class]])
            valueString = [(NSURL *)obj absoluteString];
        else
            valueString = [obj description];

        [array addObject:[NSString stringWithFormat:@"%@=%@", key, [valueString stringForHTTPPost]]];
    }];

    NSString *postString = [array componentsJoinedByString:@"&"];

    return [postString dataUsingEncoding:NSUTF8StringEncoding];
}

@end

拥有这两个类别后,我可以执行以下操作:

NSDictionary *params = @{@"client_id"     : client_id,
                         @"response_type" : response_type,
                         @"redirect_uri"  : redirect_uri,
                         @"state"         : state,
                         @"scope"         : scope,
                         @"accept"        : accept,
                         @"uid"           : uid,
                         @"withPwd"       : withPwd};

NSData *postData = [params dataForHTTPPost];
于 2013-10-07T18:43:30.743 回答
0

我建议更改缓存策略,看看是否有帮助

cachePolicy:NSURLRequestUseProtocolCachePolicy

尝试使用

cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
于 2013-10-07T20:14:57.920 回答