iPhone NSURLConnection : connectionDidFinishLoading - how to return a string to the calling method

标签 iphone string methods return nsurlconnection

我已经查看了类似的 stackoverflow 问题/答案,但我仍然感到困惑。

我是一个初学者,我真的很挣扎。使用 iPhone,我可以从 URL 下载 XML,但无法将结果字符串存储在 NSString 变量中并从调用函数中查看它。

我在自定义类中有以下声明:

@interface comms : NSObject {
    NSString *currURL, *receivedString;
    NSMutableData *receivedData;
    NSURLConnection *conn;
}

@property (copy, readwrite) NSString *currURL;
@property (copy, readonly) NSString *receivedString;
@property (nonatomic, assign) NSMutableData *receivedData;
@property (nonatomic, assign) NSURLConnection *conn;

-(void) getContentURL;

我在通讯类中有以下方法:

-(void) getContentURL
{
    NSLog( @"Begin getContentURL." );

    // Request data related.
    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] 
                                    autorelease];
    [request setURL:[NSURL URLWithString: currURL]];

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

    // Create Connection.
    conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    if (conn) {
        // The connection was established.
        receivedData = [[NSMutableData data] retain];
        NSLog( @"Data will be received from URL: %@", request.URL );
    }
    else
    {
        // The download could not be made.
        NSLog( @"Data could not be received from: %@", request.URL );
    }

    // PROBLEM - receivedString is NULL here.
    NSLog( @"From getContentURL: %@", receivedString );
}

我已按照以下方式在通信类中创建了所需的委托(delegate):

-(void)connection:(NSURLConnection *)connection didReceiveResponse:
    (NSURLResponse *)response
{
    // Discard all previously received data.
    [receivedData setLength:0];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:
(NSData *)data
{
    // Append the new data to the receivedData.
[receivedData appendData:data];     
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // Connection succeeded in downloading the request.
    NSLog( @"Succeeded! Received %d bytes of data", [receivedData length] );

    // Convert received data into string.
    receivedString = [[NSString alloc] initWithData:receivedData 
        encoding:NSASCIIStringEncoding];
    NSLog( @"From connectionDidFinishLoading: %@", receivedString );

    // release the connection, and the data object
    [conn release];
    [receivedData release];
}

我可以在connectionDidFinishLoading委托(delegate)中使用NSLog成功输出receivedString字符串。

    // Convert received data into string.
    receivedString = [[NSString alloc] initWithData:receivedData 
        encoding:NSASCIIStringEncoding];
    NSLog( @"From connectionDidFinishLoading: %@", receivedString );

但是,当我在 getContentURL 中输出 receiveString 字符串时,它为 null(因此我从其调用通讯类的 ViewController.m 类中也为 null)。

    // PROBLEM - receivedString is NULL here.
    NSLog( @"From getContentURL: %@", receivedString );

关于如何在 getContentURL 和 ViewController.m 类中查看 receiveString 的值,有什么想法吗?

最佳答案

NSURLConnection 是一个异步 API。当您启动请求时,该对象将生成一个新线程,并且仅通过回调/委托(delegate)方法更新您的主线程。您当前的方法很可能会在请求完成之前返回,因此结果的字符串尚未下载!

如果您想同步执行此操作,您将有两个选择:

  1. 使用内置的同步下载方法。请注意,当此阻塞时,它将不允许用户与 UI 交互。
  2. 使用 C 函数 CFRunLoopRun() 和 CFRunLoopStop() 在调用函数内启动运行循环,等待下载完成或失败,然后使用 CFRunLoopStop() 将控制权返回给调用方法。

关于iPhone NSURLConnection : connectionDidFinishLoading - how to return a string to the calling method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2249531/

相关文章:

iphone - iPhone:“指纹扫描仪”可以作为API使用吗?

php - 正则表达式单词前面有 char

java - 如何在java中从字符串创建唯一的整数?

python - 如何使用类方法作为参数(变量)?

iphone - 如何使用 MPMoviePlayerController 从视频文件中获取每秒实时帧数而不观看视频?

iphone - 像表格 View 单元格一样绘制游戏中心

iphone - 如何更改 "Add Contact"按钮的颜色?

java - 有没有办法使用不同的分隔符按第一个(或最大)匹配来分割Java字符串

c# - 如何在 ASP.NET Web 应用程序中的 C# 方法中执行/调用 javascript 方法

node.js - 使用服务器方法进行内存缓存中的 Hapi 不接受对象作为参数