iOS получить соединение - PullRequest
       1

iOS получить соединение

1 голос
/ 12 февраля 2012

Я впервые на этом сайте, и я очень плохо знаком с программированием, поэтому мне было интересно, может ли кто-нибудь мне помочь.

Я хочу отправить запрос на получение из приложения iphone на мой веб-сайт ивернуть информацию с веб-сайта на мой телефон.

Я зашел так далеко, но не знаю, куда идти дальше.Любая помощь будет высоко ценится, спасибо!

- (void)myData:(id)sender
{
  NSString *DataToBeSent;
  sender = [sender stringByReplacingOccurrencesOfString:@"," withString:@"%20"];
  [receivedData release];
  receivedData = [[NSMutableData alloc] init];
  DataToBeSent = [[NSString alloc] initWithFormat:@"http://194.128.xx.xxx/doCalc/getInfo.php?Data=%@",sender];
  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:dataToBeSent] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10];
  [request setHTTPMethod: @"GET"];
  NSError *requestError;
  NSURLResponse *urlResponse = nil;  
  NSData *response1 = [NSURLConnection sendSynchronousRequest:request   returningResponse:&urlResponse error:&requestError];
  [dataToBeSent release];
}

OLD WAY

- (void)myData:(id)sender
{
  NSString *dataToBeSent;
  sender = [sender stringByReplacingOccurrencesOfString:@"," withString:@"%20"];
  [receivedData release];
  receivedData= [[NSMutableData alloc] init];
  dataToBeSent= [[NSString alloc] initWithFormat:@"http://194.128.xx.xxx/doCalc/getInfo.php?Data=%@",sender];
  NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:dataToBeSent]];
  Theconn= [[NSURLConnection alloc]initWithRequest:theRequest delegate:self];
  NSLog (@"test1 %@", theRequest);
  NSLog (@"test2 %@", Theconn);
  [dataToBeSent release];
}

Затем вызываются следующие методы, и я получаю свои данные, НО, если я отправил другой запрос после моего первогоно разные данные на одном и том же соединении, это всегда дает мне один и тот же результат, который не должен происходить

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
  /* appends the new data to the received data */
  [receivedData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)conn
{
  NSString *stringData= [[NSString alloc] 
  initWithData:receivedData encoding:NSUTF8StringEncoding]; 
  NSLog(@"Got data? %@", stringData);
  [self displayAlertCode:stringData];    
  [stringData release];
  // Do unbelievably cool stuff here //
}

1 Ответ

1 голос
/ 12 февраля 2012

При условии, что ваши данные загружены правильно, вы можете преобразовать данные в строку и делать с ней все, что захотите.

NSData *response1 = [NSURLConnection sendSynchronousRequest:request   returningResponse:&urlResponse error:&requestError];

//Make sure to set the correct encoding
NSString* responseString = [[NSString alloc] initWithData:response1 encoding:NSASCIIStringEncoding];

Если ваш сервер возвращает JSON, существуют сторонние библиотеки, которые могут анализировать строку в коллекции, такие как NSArray и NSDictionary. Если ваш сервер возвращает XML, вы можете использовать NSXMLParser.

EDIT

Я изменил ваш код для управления памятью немного по-другому.

.h

@property (nonatomic,retain) NSMutableData * receivedData;
@property (nonatomic,retain) NSURLConnection * Theconn;

.m

@synthesize receivedData;
@synthesize Theconn;

//A bunch of cool stuff


- (void)myData:(id)sender
{
    //If you already have a connection running stop the existing one
    if(self.Theconn != nil){
        [self.Theconn cancel];
    }

    sender = [sender stringByReplacingOccurrencesOfString:@"," withString:@"%20"];

    //This will release your old receivedData and give you a new one
    self.receivedData = [[[NSMutableData alloc] init] autorelease];


    NSString *dataToBeSent = [NSString stringWithFormat:@"http://194.128.xx.xxx/doCalc/getInfo.php?    Data=%@",sender];

    NSURLRequest *theRequest= [NSURLRequest requestWithURL:[NSURL URLWithString:dataToBeSent]];

    //This will release your old NSURLConnection and give you a new one
    self.Theconn = [NSURLConnection connectionWithRequest:theRequest delegate:self];

    NSLog (@"test1 %@", theRequest);
    NSLog (@"test2 %@", Theconn);

 }

 //...
 //Your delegate methods
 //...

 - (void) dealloc{
    [receivedData release];
    [Theconn release];
    [super dealloc];
 }
...