我的问题是在 iOS7 上采用[NSURLConnection sendAsynchronousRequest...]
withPOST
方法失败,但在 iOS6 环境下成功。
其他信息:
在我的 iOS6 环境中可以像这样从服务器获取 JSON 数据。(成功的)
{ "status": 200, "data": [ { "oauth_token": "BVgOa01tg6JvfuXOPoJS8wB26TpvAaDs" } ] }
iOS7 上的相同代码将收到此错误消息。(失败的)
错误:错误域=NSCocoaErrorDomain 代码=3840“操作无法完成。(可可错误 3840。)”(无值。)
我检查了服务器端的 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";
}