2009-05-27 15 views
28

Devo controllare e valutare i codici di stato HTTP nella mia app per iPhone. Ho un oggetto NSURLRequest e un NSURLConnection che con successo (credo) collegarsi al sito:Recupera i codici di stato HTTPResponse/HTTPRequest iPhone SDK?

// create the request 
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.apple.com/"] 
         cachePolicy:NSURLRequestUseProtocolCachePolicy 
        timeoutInterval:60.0]; 
// create the connection with the request 
// and start loading the data 
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; 
if (theConnection) { 
    // Create the NSMutableData that will hold 
    // the received data 
    // receivedData is declared as a method instance elsewhere 
    receivedData=[[NSMutableData data] retain]; 
} else { 
    // inform the user that the download could not be made 
} 

ho ottenuto questo codice qui: http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html

ma non è così (per quanto posso vedere) dice qualcosa sull'accesso ai codici di stato HTTP.

Qualcuno ha idea di come effettuare una connessione a un sito e quindi controllare i codici di stato HTTP di quella connessione?

Grazie in anticipo!

risposta

76

Questo è come lo faccio:

#pragma mark - 
    #pragma mark NSURLConnection Delegate Methods 
    - (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response { 
     NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response; 
     int responseStatusCode = [httpResponse statusCode]; 
    } 

Ma io sto usando un NSURLConnection asincrona, quindi questo non si può aiutare. Ma spero lo faccia comunque!

+0

Questo ha portato a termine ciò di cui avevo bisogno. L'unico problema è che se l'URL/IP Addy non esiste, non viene ricevuta alcuna risposta, quindi l'app si blocca lì per sempre. Attualmente sto cercando un modo per affrontare questo ... qualsiasi suggerimento sarebbe apprezzato ... – cmcculloh

+3

Guarda il codice Reachabilty da Apple. Utilizzare solo il metodo di notifica (non abilitato nel codice per impostazione predefinita, vedere i commenti nel metodo init) e impostare sempre l'host che si desidera controllare. http://stackoverflow.com/questions/477852/checking-for-internet-connectivity-in-objective-c –