使用 Cocoa Touch 从服务器上传和下载数据?

Posted

技术标签:

【中文标题】使用 Cocoa Touch 从服务器上传和下载数据?【英文标题】:Upload and download data from server with Cocoa Touch? 【发布时间】:2009-07-30 03:01:35 【问题描述】:

如何在 Cocoa Touch 中从服务器上传/下载数据。这是我到目前为止所拥有的......

-(void)uploadSchedule:(id)sender

    NSData *content = [NSData dataWithContentsOfFile:self.dataFilePath];
    NSString *stuff = [[NSString alloc] initWithData:content encoding:NSASCIIStringEncoding];

    NSURL *url = [NSURL URLWithString:@"http://thetis.lunarmania.com"];
    NSMutableURLRequest* urlRequest = [[NSMutableURLRequest alloc]initWithURL:url];
    [urlRequest setHTTPMethod:@"POST"];
    [urlRequest setHTTPBody:[stuff dataUsingEncoding:NSASCIIStringEncoding]];

    NSLog(@"great success!");


-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

    // this method is called when the server has determined that it
    // has enough information to create the NSURLResponse

    // it can be called multiple times, for example in the case of a
    // redirect, so each time we reset the data.
    // receivedData is declared as a method instance elsewhere

    [receivedData setLength:0];


-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

    // append the new data to the receivedData
    // receivedData is declared as a method instance elsewhere

    [receivedData appendData:data];


-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

    // release the connection, and the data object
    [connection release];
    // receivedData is declared as a method instance elsewhere
    [receivedData release];

    // inform the user
    NSLog(@"Connection failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSErrorFailingURLStringKey]);


-(void)connectionDidFinishLoading:(NSURLConnection *)connection

    // do something with the data
    UIImage *image = [[UIImage alloc] initWithData:receivedData];
    [cat setImage:image];
    [image release];

    // receivedData is declared as a method instance elsewhere
    NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);

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


-(void)connection:(NSURLConnection *)connection
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge

    if ([challenge previousFailureCount] == 0) 
        NSURLCredential *newCredential;
        newCredential=[NSURLCredential credentialWithUser:@"ican@moeyo.org"
                                                 password:@"icanican"
                                              persistence:NSURLCredentialPersistenceNone];
        [[challenge sender] useCredential:newCredential
               forAuthenticationChallenge:challenge];
     else 
        [[challenge sender] cancelAuthenticationChallenge:challenge];
        // inform the user that the user name and password
        // in the preferences are incorrect
        //[self showPreferencesCredentialsAreIncorrectPanel:self];
    

我很迷茫……

【问题讨论】:

【参考方案1】:

代码崩溃是因为你过度释放connection。查看Cocoa memory management rules。

除此之外,您还必须更具体地说明您遇到的问题。

顺便说一句,术语是“实例变量”,而不是“方法实例”。实例变量是实例内部的变量,与方法无关。

【讨论】:

【参考方案2】:

这里已经介绍过:

NSURLRequest - encode url for NSURLRequest POST Body (iPhone objective-C)

接受的答案使用ASIHTTPRequest,这与我使用过的类似,并且可以很容易地从 html 表单中发布/获取。这是一个示例(来自过去的 ***)

ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:@"http://someSite.com"] autorelease];
[request setPostValue:@"myValue1" forKey:@"myFormField1"];
[request setPostValue:@"myValue2" forKey:@"myFormField2"];
// etc.
[request start];
NSError *error = [request error];
if (!error)
  NSString *response = [request responseString];

【讨论】:

【参考方案3】:

如果你的文件很大,最好使用NSFilehandle,将数据写入didReceiveData,而不是追加。

【讨论】:

以上是关于使用 Cocoa Touch 从服务器上传和下载数据?的主要内容,如果未能解决你的问题,请参考以下文章

Cocoa Touch 从 Core Data 更新 UITableView

从数组(plist)中删除字典元素 Cocoa Touch

UI - Cocoa Touch框架

静态 cocoa/cocoa-touch 库应该基于啥样的 SDK?

如何从 UIImage (Cocoa Touch) 或 CGImage (Core Graphics) 获取像素数据?

cocoa 和 cocoa touch的区别