2010-12-08 15 views
9

NSURLProtocol'u geçersiz kılar ve belirli bir statusCode ile HTTP yanıtını döndürmeliyim. NSHTTPURLResponse statusCode ayarlayıcı yok, bu yüzden bu değeri geçersiz kılabilir denedi:NSURLResponse durumunda durum kodu nasıl ayarlanır

@interface MyHTTPURLResponse : NSHTTPURLResponse {} 

@implementation MyHTTPURLResponse 

    - (NSInteger)statusCode { 
     return 200; //stub code 
    } 
@end 
NSURLProtocol ait

Bastırıldı startLoading yöntemi aşağıdaki gibidir:,

-(void)startLoading 
{ 
    NSString *url = [[[self request] URL] absoluteString]; 
    if([url isEqualToString:SPECIFIC_URL]){ 
     MyURLResponse *response = [[MyURLResponse alloc] initWithURL:[NSURL URLWithString:@"http://fakeUrl"] 
     MIMEType:@"text/plain" 
     expectedContentLength:0 textEncodingName:nil]; 

     [[self client] URLProtocol:self  
      didReceiveResponse:response 
      cacheStoragePolicy:NSURLCacheStorageNotAllowed]; 

     [[self client] URLProtocol:self didLoadData:[@"Fake response string" 
      dataUsingEncoding:NSASCIIStringEncoding]]; 

     [[self client] URLProtocolDidFinishLoading:self];     

     [response release]; 

    } 
    else{ 
     [NSURLConnection connectionWithRequest:[self request] delegate:self]; 
    } 
} 

Ama bu yaklaşım çalışmaz NSURLProtocol oluşturulan tepkiyi Web sayfasındaki statusCode = 0 ile her zaman. Aynı zamanda, NSURLConnection tarafından ağdan döndürülen yanıtların normal beklenen statusCodes'ları vardır.

Oluşturulan NSURLResponse için statusCode'u açıkça nasıl belirleyeceğiniz konusunda fikir sahibi olan herkes yardımcı olabilir mi? Teşekkürler.

+0

Bu soruna bir çözüm buldunuz mu? – TomSwift

cevap

4

: Burada

NSInteger statusCode = 200; 
    id headerFields = nil; 
    double requestTime = 1; 

    SEL selector = NSSelectorFromString(@"initWithURL:statusCode:headerFields:requestTime:"); 
    NSMethodSignature *signature = [self methodSignatureForSelector:selector]; 

    NSInvocation *inv = [NSInvocation invocationWithMethodSignature:signature]; 
    [inv setTarget:self]; 
    [inv setSelector:selector]; 
    [inv setArgument:&URL atIndex:2]; 
    [inv setArgument:&statusCode atIndex:3]; 
    [inv setArgument:&headerFields atIndex:4]; 
    [inv setArgument:&requestTime atIndex:5]; 

    [inv invoke]; 
+0

Cevabınız için teşekkür ederiz. Ben senin çözümünü denedim ve statusCode 200 var. Bu benim sorunumu çözer, tam olarak statüye 200 ihtiyacım vardı. Ama keyfi durum belirleyemedim: statusCode NSInvocation statusCode tarafından başlatılırken ne olursa olsun NSHTTPURLResponse hazırda 200. Başka statusCodes denediniz mi? ? Her neyse, bunu bir cevap olarak işaretliyorum, thnx. – okonov

+0

Sadece denedim - herhangi bir durum kodunu ayarlayabilirim (215 ayarladım). Ve bu aynı web sayfasında - 215. –

4

Durum kodunu yalnızca URLResponse'den alın. Gerek açıkça ayarlamak için: -

Aşağıdaki kodu kullanarak özel init yöntemini uyguladık
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError]; 

    NSString *responseString = [[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] autorelease]; 
    NSLog(@"ResponseString:%@",responseString); 

    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; 
    int statusCode = [httpResponse statusCode]; 
    NSLog(@"%d",statusCode); 
+0

Cevabınız için teşekkür ederiz. Ama ağdan http yanıtının statusCode değerini almam gerekmiyor. NSURLResponse'yi geçersiz kılma NSURLProtocol içine döndürmek için kendim yaratıyorum ve yanıtın statusCode değerini ayarlamanız gerekiyor. – okonov

9

daha iyi bir çözümdür.

iOS 5.0 ve üzeri sürümlerde, özel API'lerle ya da NSHTTPURLResponse aşırı yüklemeyle ilgili bir şey yapmanız gerekmez.

artık basitçe kullanabilirsiniz, kendi durum kodu ve başlıkları içeren bir NSHTTPUTLResponse oluşturmak için: üretilen belgelerde belgelenmiştir

initWithURL:statusCode:HTTPVersion:headerFields: 

ama da NSURLResponse.h başlık dosyasında aslında mevcut ve olduğu OS X 10.7 ve iOS 5.0'da kullanılabilen bir genel API olarak işaretlendi.

Ayrıca not size uygun Access-Control-Allow-Origin başlığı ayarlamak gerekir ki bir UIWebView dan XMLHTTPRequest arama yapmak için NSURLProtocol hile kullanıyorsanız söyledi. Aksi halde XMLHTTPRequest güvenlik devreye girer ve NSURLProtocol numaranız isteğinizi alıp işleme koysa bile, geri yanıt gönderemezsiniz.

İlgili konular