如何知道url中是否存在数据

时间:2011-03-21 14:30:11

标签: iphone json url

我编写了这样的代码,但我无法理解如何查找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 个答案:

答案 0 :(得分:1)

应用终止在哪里,什么是例外?您是否已逐步查看每次迭代期间数组对象的外观?它是否在NSData initWithContentsOfURL失败?为什么不将它作为单独的同步请求发出并测试以确定是否有响应?

关于你的第一个(以及任何后续的)同步请求,最好添加一个检查以确保你收到一个有效的响应(抱歉格式化,代码标签目前没有很好地播放)

if (response!=nil) {if([response isKindOfClass:[NSHTTPURLResponse class]]) {
// you have a valid response }}