从网站检索数据到iphone

时间:2012-01-22 22:43:52

标签: objective-c ios xcode

我最近在看一个关于NSURLConnection的苹果的例子,我尝试在我的代码中实现它,但我不确定我是否做得对。

基本上我想要连接到我的网站,我将它连接到在我的数据库中运行搜索的php脚本,然后将它回显给浏览器。我希望iphone采用回显的行并将其保存到字符串变量中。这是我的代码。 这是否正确完成?

提前谢谢

  NSString *stringToBeSent= [[NSString alloc] initWithFormat:
    @"http:/xxxxx/siteSql.php?  data=%@",theData];

      NSURLRequest *theRequest=[NSURLRequest requestWithURL:
      [NSURL URLWithString:stringToBeSent]
      cachePolicy:NSURLRequestUseProtocolCachePolicy
     timeoutInterval:60.0];


   // create the connection with the request
    // and start loading the data
 NSURLConnection *theConnection=[[NSURLConnection alloc] 
 initWithRequest:theRequest  delegate:self];


   if (theConnection) {
    // Create the NSMutableData to hold the received data.
    // receivedData is an instance variable declared elsewhere... in my .h file
    // NSMutableData *receivedData; 

    receivedData = [[NSMutableData data] retain];

     //convert NSMutableData to a string
    NSString *stringData= [[NSString alloc] 
      initWithData:receivedData encoding:NSUTF8StringEncoding];

    NSLog (@"result%@", receivedData);

    } else {
    // Inform the user that the connection failed.


    NSLog(@"failed");

      }

1 个答案:

答案 0 :(得分:1)

我想你可能会遗漏几件事:

  1. 在用于触发检索数据的方法中,请确保在初始化之前释放旧数据:

    [retrievedData release];
    retrievedData=[[NSMutableData alloc] init];
    
  2. 我认为空格是拼写错误或URL的某些内容?

  3. 您无需致电requestWithURL:cachePolicy:timeoutInterval: requestWithURL:使用与您选择的相同的默认设置。

  4. 数据将以块的形式出现。除了这个方法之外,你必须使用委托方法connection:didReceiveData:来处理这个问题,如下所示:

    - (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data
    {
         [receivedData appendData:data];
    }
    
  5. 同样,如果您希望在收到数据之后完成某些操作,请在connectionDidFinishLoading:中执行此操作。请注意,连接已发布,因此必须在标头中将其定义为实例变量(例如。NSURLConnection *connection;

    - (void)connectionDidFinishLoading:(NSURLConnection *)conn
    {
       NSString *stringData= [[NSString alloc] 
       initWithData:receivedData encoding:NSUTF8StringEncoding]; 
       NSLog(@"Got data? %@", stringData);
       [connection release];
        connection = nil;
       // Do unbelievably cool stuff here //
    }
    
  6. 另请查看其他委托方法,例如connection:didFailWithError:如果出现错误,您可能也希望在那里释放连接和stringData。

  7. 我希望有一些帮助!请享用!

相关问题