-1

我只是IOS开发的新手。我一直在试图找出苹果的文件。所以我读了这个页面:

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html#//apple_ref/doc/uid/20001836-BAJEAIEE

这就是我所做的:

NSMutableData *testFileType;
// Create the request.
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]
                                              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.
    testFileType = [[NSMutableData data] retain];
    NSLog(@"the connection is successful");
} else {
    // Inform the user that the connection failed.
    NSLog(@"the connection is unsuccessful");
}

[testFileType setLength:0];
[testFileType appendData:[NSMutableData data]];

谁能告诉我我在这里错过了什么?

4

2 回答 2

0

您应该实现以下委托方法:

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"Error: %d %@", [error code], [error localizedDescription]);
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    responseData = [NSMutableData data];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [responseData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [responseData writeToFile:savePath atomically:YES]; 
}

这里 responseData 和 savePath 是声明的实例变量:

NSMutableData *responseData;
NSString *savePath;

并且您的课程必须符合NSURLConnectionDataDelegateandNSURLConnectionDelegate协议。

为了使代码正常工作,您可能需要将 savePath 设置为这样的工作路径

NSString *savePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"testfile.txt"];

下载完成后,您可以根据需要对文件进行任何操作savePath

于 2012-12-18T06:25:26.340 回答
0

仅仅创建 NSURLConnection 是不够的。您还需要实现 didReceiveResponse 和 didFinishLoading 委托方法。没有这些,连接会下载文件,但你永远看不到它。

当收到标头时,NSURLConnection 会为每个重定向发送一个 didReceiveResponse。然后它发送一个带有文件的一些字节的 didReceiveData。您需要附加到可变数据的那些。最后你会得到一个 didFinishLoading ,你知道你已经得到了所有的数据。如果出现错误,您会得到一个 didFailWithError 代替。

查看 NSURLConnectionDelegate 协议文档:https ://developer.apple.com/library/mac/ipad/#documentation/Foundation/Reference/NSURLConnectionDelegate_Protocol/Reference/Reference.html

于 2012-12-18T05:49:36.627 回答