Как узнать, что данные в URL отсутствуют - PullRequest
0 голосов
/ 21 марта 2011

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

Примечание: Этот код завершается, когда цикл входит во второе условие.Вот где это заканчивается.

-(void)getdetails
{   

    NSLog(@"in get details");
    NSURL *jsonurl=[NSURL URLWithString:@"http://www.myappdemo.com/checkout/services/getonlineusers.php"];
    NSMutableURLRequest *request=[[[NSMutableURLRequest alloc]init ]autorelease];

    [request setURL:jsonurl];
    [request setHTTPMethod:@"POST"];

    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

    NSError *error;
    NSURLResponse *response;
    NSData *serverReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *replyString = [[NSString alloc] initWithBytes:[serverReply bytes] length:[serverReply length] encoding: NSASCIIStringEncoding];

    if([replyString isEqualToString:@"Invalid."]){ // i have not set the php code to output "invalid" so this will not work for now ...

        NSLog(@"%@",replyString);
    }
    else {
        NSMutableArray *tempArray =[replyString JSONValue];

        int count=0;
        self.temparray=tempArray;

        for(int i=0;i<[tempArray count];i++)
        {
            ///////Here in this loop when it is entering it is terminating /////////

            NSDictionary *dict=[tempArray objectAtIndex:i];
            NSLog(@"DICT is %@",dict);

            NSString *string=[dict objectForKey:@"profilepic"];
            NSURL *finalURL = [NSURL URLWithString:[string stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
            NSLog(@"encoding string is %@",finalURL);
            NSURL *url=[NSURL URLWithString:string];
            NSString *source = [NSString stringWithContentsOfURL:finalURL encoding:NSUTF8StringEncoding error:nil];
            NSFileManager *fileManager = [NSFileManager defaultManager];
            BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:url];
            NSLog(@"url is %@",url);
            NSData *data=[NSData  dataWithContentsOfURL:url];

            if(!(data==nil))
            {
        NSLog(@"data is there");

                UIImage *image=[[UIImage alloc]initWithData:data];

                [self.array addObject:image];
                [image release];
            }
            else {
                /*
                NSLog(@"if data is null condition block");
                UIImage *image=[[UIImage alloc]init];
                [self.array addObject:image];
                [image release];    
                */
            }

            count=count+1;

            NSLog(@"count is %d",count);

        }

    }

    [replyString release];
}

1 Ответ

1 голос
/ 21 марта 2011

Где заканчивается приложение и что является исключением? Вы прошли, чтобы увидеть, как выглядит объект массива во время каждой итерации? Это терпит неудачу в NSData initWithContentsOfURL? Почему бы вам не выдать это как отдельный синхронный запрос и проверить, получили ли вы ответ?

Что касается вашего первого (и любого последующего) синхронного запроса, вероятно, было бы целесообразно добавить проверку, чтобы убедиться, что вы получили правильный ответ (извините за форматирование, кодовый тег в настоящее время не воспроизводится)

if (response!=nil) {if([response isKindOfClass:[NSHTTPURLResponse class]]) {
// you have a valid response }}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...