Получить ответ php-сайта в Objective-C - PullRequest
1 голос
/ 11 марта 2012

У меня есть сайт php, который возвращает ДА ​​или НЕТ по запросу.Например,

www.test.com / test.php? Variable = test1 вернет мне ДА, а www.test.com/test.php?variable=test2 вернет мне НЕТ

Iя пытаюсь получить этот ответ в приложении Objective-C, которое я создаю, но мне пока не повезло.Вот мой код

NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.test.com/test.php?variable=test1"]
                                          cachePolicy:NSURLRequestUseProtocolCachePolicy
                                      timeoutInterval:60.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
    NSMutableData *receivedData = [NSMutableData data];
    NSString *strData = [[NSString alloc]initWithData:receivedData encoding:NSUTF8StringEncoding];
    NSLog(@"This is the response: %@", strData);
}else {
 }

Кто-нибудь может мне помочь в этом?Есть ли другой способ сделать это?Я делаю что-то не так?

Большое спасибо, ребята

Ответы [ 2 ]

2 голосов
/ 11 марта 2012
     - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
        {
            [receivedData appendData:data];
        // declre receivedData as a property of the class(in xxx.m)
            NSError *error=nil;
            NSDictionary *result=[NSJSONSerialization JSONObjectWithData:data options:
                                  NSJSONReadingMutableContainers error:&error];
            NSLog("%@", result);
    //do whatever you want...

           //the result dictionary is a JSON object and you can use it as KVC(key-value-coding) rules  
 }

Если ваше приложение предназначено для iOS 5, просто используйте этот код в файле xxx.m в соответствии с методом, который вы создали для запроса. И если вы хотите использовать его в некоторых других версиях iOS, взгляните на рамки JSON-анализатора ..

0 голосов
/ 11 марта 2012

Кажется, вы правильно настраиваете соединение.Однако затем вам нужно перехватить данные в методах NSURLConnection Delegate, описанных в файле NSURLConnection.h:

@protocol NSURLConnectionDataDelegate <NSURLConnectionDelegate>
@optional
- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response;
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;

- (NSInputStream *)connection:(NSURLConnection *)connection needNewBodyStream:(NSURLRequest *)request;
- (void)connection:(NSURLConnection *)connection   didSendBodyData:(NSInteger)bytesWritten
                                                 totalBytesWritten:(NSInteger)totalBytesWritten
                                         totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite;

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse;

- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
@end

Особый интерес представляют didReceiveData и connectionDidFinishLoading.

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