网页完成加载后读取数据

时间:2013-06-20 02:19:37

标签: ios objective-c http connection

我在iOS上制作一个登录方法,通过url向PHP页面发送GET请求,当我尝试从网站读取输出时,在PHP完成mysql查询之前读取数据,我很想知道如果有任何方法等待网页完全加载,从中读取数据 代码:

-(NSString *)getWebpageData:(NSString *)url {
    NSURL *URL = [NSURL URLWithString:url];
    NSError *error = nil;
    NSString *content = [NSString stringWithContentsOfURL:URL encoding:NSUTF8StringEncoding error:&error];
    return content;
}

1 个答案:

答案 0 :(得分:0)

我会尝试使用NSURLConnection通过sendAsynchronousRequest这样......

NSOperationQueue *myQueue = [[NSOperationQueue alloc]init];
    [NSURLConnection sendAsynchronousRequest:request queue:myQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
        //do something
    }];

当处理程序块被解雇时,您可以获得内容。

另一种选择是调用NSURLConnectionDataDelegate。当你调用你的URL时,它会触发一些方法让你知道什么时候完成。

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    //Fired on error
}

- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
{
    //Fired First
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    //Fired Second
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    //Fired Third
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    //Fired Fourth
}

使用委托方法,您可能希望利用didReceiveData,以便将数据放在那里。祝你好运。