0

我使用asiformdatarequest框架上传图片,代码如下:

 NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *path1=[paths objectAtIndex:0];
    NSString *filename=[path1 stringByAppendingPathComponent:@"logo.png"];  
    NSLog(@"image path = %@",filename);
    [request setFile:[NSURL URLWithString:filename] forKey:@"avatar"];
    [request startSynchronous];

我的日志:

image path = /Users/tanlusheng/Library/Application Support/iPhone Simulator/5.1/Applications/5473E6FF-0D3A-48CD-8728-0219CF25BC80/Documents/logo.png
Error Domain=ASIHTTPRequestErrorDomain Code=6 "No file exists at (null)" UserInfo=0x6b4c610 {NSLocalizedDescription=No file exists at (null)}

我在我的项目中添加了一张图片。但为什么找不到文件?我在模拟器中运行。

4

1 回答 1

0

当您尝试发送图像时,您是在尝试从应用程序Documents目录发送图像,而不是主包。除非您已将图像显式放置在Documents目录中(您很可能通过代码执行此操作),否则它不会存在。

试试这个:

NSString *filename = [[NSBundle mainBundle] pathForResource:@"logo" ofType:@"png"];  
[request setFile:[NSURL URLWithString:filename] forKey:@"avatar"];
[request setDelegate:self]; //Make sure this class receives request alerts
[request setDidFinishSelector:@selector(someMethod:)]; //Which method to call when finished
[request startAsynchronous];

注意我还更改了异步启动的请求。您真的不想同步上传,否则您的应用程序将停止执行,直到请求完成。我还添加了自我委托和请求完成时的选择器。

然后,您可以在此处处理已完成的查询:

- (void)someMethod:(ASIHTTPRequest *)request
{
    NSString *response = [request responseString];
    NSLog(@"%@", response);
}

如果您仍然收到 null 错误,请确保图像具有Target Membership。为此,请在 Xcode 中选择您的图像,并确保在右侧的Target Membersip下勾选了小框。这将确保图像在构建时是应用程序的一部分。

于 2012-05-10T12:47:03.997 回答