2014-01-02 4 views
0

Я пытаюсь написать класс, который я могу использовать для создания запросов HTTP Post и получения результатов запроса. Что-то не совсем связано, потому что я не получаю никаких подтверждений, даже сообщений о сбоях. Мои первые два NSLogs генерируются, но из методов соединения ничего не возвращается. Ничего не происходит, он просто не возвращается. Вот только выход, который я получаю:Написание iOS http Класс post

&first=vic&second=tory 
www.mySite.com/phpTest.php 

Я могу успешно сделать простые запросы HTTP, так что я знаю, что моя проблема не связана с подключением и тому подобное. Кроме того, на данный момент этот php-скрипт игнорирует параметры, которые я отправляю им, чтобы я мог максимально упростить это для тестирования/отладки. Все, что должно произойти, это то, что слово «успех» должно быть возвращено.

Может ли кто-нибудь увидеть, что происходит не так? Спасибо!

Вот мой метод вызова:

- (IBAction)phpTest:(UIBarButtonItem *)sender 
{ 
    //set post string with actual parameters 
    NSString *post = [NSString stringWithFormat:@"&first=%@&second=%@", @"vic", @"tory"]; 
    NSString *script = @"phpTest.php"; 

    NSLog(@"%@", post); 

    MyDownloader *d = [[MyDownloader alloc] initWithPost:post script:script]; 

    [[NSNotificationCenter defaultCenter] addObserver:self 
              selector:@selector(finished:) 
               name:@"connectionFinished" 
               object:d]; 

    [d.connection start]; 

} 

- (void) finished: (NSNotification *) n 
{ 
    MyDownloader *d = [n object]; 
    NSData *data = nil; 
    if ([n userInfo]) { 
     NSLog(@"information retrieval failed"); 
    } else { 
     data = d.receivedData; 
     NSString *text=[[NSString alloc]initWithData:d.receivedData encoding:NSUTF8StringEncoding]; 
     NSLog(@"%@", text); 

    } 

    [[NSNotificationCenter defaultCenter] removeObserver:self 
                name: @"connectionFinished" 
                object:d]; 

} 

MyDownloader.m

@interface MyDownloader() 

@property (nonatomic, strong, readwrite) NSURLConnection *connection; 
@property (nonatomic, copy, readwrite) NSMutableURLRequest *request; 
@property (nonatomic, copy, readwrite) NSString *postString; 
@property (nonatomic, copy, readwrite) NSString *script; 
@property (nonatomic, strong, readwrite) NSMutableData *mutableReceivedData; 
@end 

@implementation MyDownloader 

- (NSData *) receivedData 
{ 
    return [self.mutableReceivedData copy]; 
} 

- (id) initWithPost: (NSString *)post 
      script : (NSString *)script 
{ 
    self = [super init]; 

    if (self) { 
     self->_postString = post; 
     self->_script = script; 
     self->_connection = 
      [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO]; 
     self->_mutableReceivedData = [NSMutableData new]; 
    } 

    //Encode the post string using NSASCIIStringEncoding and also the post string you need to send in NSData format. 
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 

    //You need to send the actual length of your data. Calculate the length of the post string. 
    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]]; 

    //Create a Urlrequest with all the properties like HTTP method, http header field with length of the post string. 
    //Create URLRequest object and initialize it. 
    self.request = [[NSMutableURLRequest alloc] init]; 

    // make a string with the url 
    NSString *url = [@"www.mySite.com/" stringByAppendingString:script]; 
    NSLog(@"%@", url); 

    // Set the Url for which your going to send the data to that request. 
    [self.request setURL:[NSURL URLWithString:url]]; 

    //Now, set HTTP method (POST or GET). 
    [self.request setHTTPMethod:@"POST"]; 

    //Set HTTP header field with length of the post data. 
    [self.request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 

    //Also set the Encoded value for HTTP header Field. 
    [self.request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"]; 

    // Set the HTTPBody of the urlrequest with postData. 
    [self.request setHTTPBody:postData]; 

    return self; 
} 

- (void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *)response 
{ 
    [self.mutableReceivedData setLength:0]; 
    NSLog(@"didReceiveRespongs"); 
} 

- (void) connection:(NSURLConnection *) connection didReceiveData:(NSData *)data 
{ 
    [self.mutableReceivedData appendData:data]; 
    NSLog(@"didReceiveData"); 
} 

- (void) connection:(NSURLConnection *) connection didFailWithError:(NSError *)error 
{ 
    [[NSNotificationCenter defaultCenter] 
     postNotificationName:@"connectionFinished" 
     object:self userInfo:@{@"error":error}]; 

    NSLog(@"-connection:didFailWithError: %@", error.localizedDescription); 
} 

- (void) connectionDidFinishLoading:(NSURLConnection *) connection 
{ 
    [[NSNotificationCenter defaultCenter] 
     postNotificationName:@"connectionFinished" object:self]; 
    NSLog(@"didFinishLoading"); 
} 

- (void) cancel 
{ 
    // cancel download in progress, replace connection, start over 
    [self.connection cancel]; 
    self->_connection = 
     [[NSURLConnection alloc] initWithRequest:self->_request delegate:self startImmediately:NO]; 
} 

@end 
+0

print_r ваш массив $ _POST в конце PHP и поделиться тем, что вы получаете – Retro

+0

просто нажмите на ссылку, что я дал, и вы увидите его в вашем браузере. Как я уже упоминал в своем посте, в моем симуляторе ничего не получается. – Alex

+0

ya но я хочу знать, что php получает данные, которые вы пытаетесь отправить из объектива c – Retro

ответ

2

Три вещи:

  1. , как вы настроили URL для NSURLRequest является недействительным. Эта строка отсутствует схема URL:

    NSString *url = [@"www.example.com/" stringByAppendingString:script]; 
    

    и должно быть:

    NSString *url = [@"http://www.example.com/" stringByAppendingString:script]; 
    
  2. В initWithPost:Script:, вы создаете NSURLConnection объект с объектом запроса, который nil. Эта строка:

    self->_connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO]; 
    

    следует переместить в линию после [self.request setHTTPBody:postData];.

  3. В initWithPost:Script:, используя self-> не нужно. Вы можете получить доступ к Ивар просто как _postString и т.д.

+0

Спасибо! Это решило проблему. Не могу вас поблагодарить! – Alex