2

这是我的第一个IOS项目。很难登录工作。该站点有一个指向另一个 url 的 meta_refresh。我试图向 meta_refresh 中的 url 发送另一个请求,但是应用程序只是挂起。我确定我做错了什么,但我使用的是 XCode 4.4,所以很多 NSURLConnection 委托方法已被弃用。

这就是我正在做的事情:

NSString *urlAsString = baseURL;
urlAsString = [urlAsString stringByAppendingString:@"?user[login]=username"];
urlAsString = [urlAsString stringByAppendingString:@"&user[password]=password"];
urlAsString = [urlAsString stringByAppendingString:@"&origin=splash"];

NSURL *url = [NSURL URLWithString:urlAsString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setTimeoutInterval:30.0f];
[urlRequest setHTTPMethod:@"POST"];
NSURLResponse *response = nil;
NSError *error = nil;

NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];    

if([data length] > 0 && error == nil){
    NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"HTML = %@", html);
    NSRange obj = [html rangeOfString:@"http-equiv=\"refresh\""];
    NSInteger len = obj.length;
} else if([data length] == 0 && error == nil) {
    NSLog(@"No data was returned.");

} else {
    NSLog(@"Error happened = %@", error);
}

这是我得到的:

另一个问题是我读过我应该使用异步连接。问题是我需要从网站上抓取的数据显示在屏幕上。如果我在返回数据之前显示屏幕,那么我将没有任何数据——或者我不明白这是如何工作的?

谢谢。——托尼

4

1 回答 1

1

I think that maybe you're a mixing stuff. You're setting a string url with GET values and then you set the HTTPMethod to POST and I don't know if that is going to work fine.

Here's a code that I have to send values with POST:

NSString *post = [NSString stringWithFormat:@"&user_login=%@&user_password=%@&origin=%@,username,password, splash];

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:baseURL]]];

[request setHTTPMethod:@"POST"];

[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postData];

NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
于 2012-11-12T16:00:41.797 回答