iPhone - Call a php page asynchronously and be sure it has been loaded

前端 未结 1 1641
我在风中等你
我在风中等你 2021-01-23 18:29

In one of my apps, I\'d like to call asynchronously a php page I have written (http://serveradress/page.php?date=20111231), and I would be sure to know if the page could be call

相关标签:
1条回答
  • 2021-01-23 18:51

    NSURLConection is very good solution for asynchronous loading. There are few steps for creating one.

    1. Setup your NSURLConnection

    - (void)viewDidLoad {
        // your code...
        responseData = [[NSMutableData alloc] init];
        NSURL *url = [NSURL URLWithString:@"http://yourdomain.com/"];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]];
    }
    

    responseData is your NSMutableData iVar.

    2. Implement delegate methods

    a) In this method we will check for HTTP status codes

    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
        if ([response respondsToSelector:@selector(statusCode)]) {
            int statusCode = [((NSHTTPURLResponse *)response) statusCode];
            if (statusCode >= 400) {
                [connection cancel]; 
                NSDictionary *errorInfo = [NSDictionary dictionaryWithObject:[NSString stringWithFormat:NSLocalizedString(@"Server returned status code %d",@""),statusCode] forKey:NSLocalizedDescriptionKey];
                NSError *statusError = [NSError errorWithDomain:NSHTTPPropertyStatusCodeKey code:statusCode userInfo:errorInfo];
               [self connection:connection didFailWithError:statusError];
            }
        }
    }
    

    b) This creates your NSData component

    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
        [responseData appendData:data];
    }
    

    c) Handles successful url connection

    - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
        // do whatever you want using responseData as your server output
    }
    

    d) Handles errors

    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
        // handle your error
    }
    

    You can get error info using [error userInfo] And display it in UIAlertView, for example.


    So as I said NSURLConnection is very good solution, but you should also look at ASIHTTPRequest library. :)

    0 讨论(0)
提交回复
热议问题