【问题标题】:Receiving data from URL on iPhone?从 iPhone 上的 URL 接收数据?
【发布时间】:2009-02-27 08:06:42
【问题描述】:

我正在使用 Apple Document 创建一个应用程序。我成功连接到服务器,但我从服务器收到 0 个字节(没有响应数据)。我采取以下步骤:

  1. 我创建了一个基于视图的应用程序并添加了一个属性“receivedData”:

    在 ViewController.h 中:

    @property (nonatomic, retain) NSMutableData *receivedData;

    在 ViewController.m 中:

    @synthesize receivedData; 
  2. ViewController.m 的动作 'ViewDidLoad',我补充一下:

    receivedData = [NSMutableData alloc];
  3. 在视图中添加一个按钮并为其添加操作:

    // create the request
    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://..."]
                        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 that will hold
    // the received data
    // receivedData is declared as a method instance elsewhere
    receivedData=[[NSMutableData data] retain];
    } else {
    // inform the user that the download could not be made
    }

当我调试这些代码时,我发现 receivedData 返回 0 个字节。关于出了什么问题的任何想法?对我的代码进行简单修改将不胜感激。

【问题讨论】:

    标签: iphone http nsurlconnection communication


    【解决方案1】:

    您的代码仅创建 HTTP 连接 - 只有在框架调用委托回调后(一旦收到 HTTP 响应),数据才会被写入并在 receivedData 中可用。您可以从Apple's documentation获取更多信息和示例代码

    【讨论】:

    • 谢谢。添加了带有'didReceiveData'的方法,我成功地从服务器接收到数据。
    【解决方案2】:

    答案与我上次在How can I receive data from URL on iPhone? 为您回答时相同。我做了详细的解释,你看了吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-08
      • 1970-01-01
      • 2012-01-14
      • 2018-03-22
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多