4

所以我有一个 iPhone 应用程序需要:

  1. 将多个字符串和最多 5 张图像(存储在内存中)发布到 RoR Web 应用程序
  2. 解析返回的 JSON,该 JSON 将包括几个字符串和一组 URL(每个都表示可以在网站上找到上传图像的位置)。

问题:

  1. 这可以用 Three20 完成吗(会很好,因为我将它用于其他事情)?如果是这样,怎么办?

  2. 如果它不能用 Three20 完成......如何使用 ASIHttpRequest 完成?或者,如果这是一个更好的选择,也许会在 SDK 中加入一些东西?

非常感谢

4

2 回答 2

4

不幸的是,网络上没有很多关于three20的教程和好的文档......所以这就是我最终如何让事情发挥作用的方式:

- (void) sendToWebsite {

    NSString* url = [[NSString stringWithFormat:kRequestURLPath, self.entityId] stringByAppendingString:@".json"] ;

    // Prep. the request
    TTURLRequest* request = [TTURLRequest requestWithURL: url delegate: self];
    request.httpMethod = @"POST";
    request.cachePolicy = TTURLRequestCachePolicyNoCache; 

    // Response will be JSON ... BUT WHY DO I NEED TO DO THIS HERE???
    request.response = [[[TTURLJSONResponse alloc] init] autorelease];

    // Set a header value
    [request setValue:[[UIDevice currentDevice] uniqueIdentifier] forHTTPHeaderField:@"Device-UID"];

    // Post a string
    [request.parameters setObject:self.entity_title forKey:@"entity_title"];

    // Post some images
        for (int i = 0; i < [self.photos count]; i++) {
        // IS IT POSSIBLE TO ADD A PARAM NAME SO I CAN LOOK FOR THE SAME NAME
        // IN THE WEB APPLICATION REGARDLESS OF FILENAME???
        [request addFile:UIImagePNGRepresentation([self.winnerImages objectAtIndex:i]) 
                mimeType:@"image/png" 
                fileName:[NSString stringWithFormat:@"photo_%i.png", i]];
    }

        // You rails guys will know what this is for
        [request.parameters setObject:@"put" forKey:@"_method"];

        // Send the request
    [request sendSynchronously];

}

我仍然不明白(或发现有问题)的事情:

  1. 对于发布的文件,如何同时包含参数名称和文件名?
  2. 将 request.response = 设置为什么的目的是什么?我不明白。
于 2010-05-18T18:11:38.690 回答
1

回答 #2:您需要在发送请求之前为响应提供处理程序TTURLJSONResponse,这不是实际的响应,但它负责处理响应。这是您处理字符串和 URL 数组的响应的地方。

它实际上是一个名为的协议TTURLResponse,它定义了以下实现方法:

/**
 * Processes the data from a successful request and determines if it is valid.
 *
 * If the data is not valid, return an error. The data will not be cached if there is an error.
 *
 * @param  request    The request this response is bound to.
 * @param  response   The response object, useful for getting the status code.
 * @param  data       The data received from the TTURLRequest.
 * @return NSError if there was an error parsing the data. nil otherwise.
 *
 * @required
 */
- (NSError*)request:(TTURLRequest*)request 
            processResponse:(NSHTTPURLResponse*)response
            data:(id)data;

您选择了TTURLJSONResponse作为您的处理程序,这是一个直接的实现,可以帮助您编写自己的代码。

于 2011-02-21T17:02:50.083 回答