【问题标题】:send date to server and get a string back将日期发送到服务器并返回一个字符串
【发布时间】:2014-01-03 20:43:57
【问题描述】:

我正在向我的服务器发送用户详细信息,它应该以字符串形式返回用户 ID, 在我的服务器接收到的数据我可以得到字符串。

代码:

NSString *urlStr = [NSString stringWithFormat:@"url/////api/%@/%@",
                        [Email.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
                        [Password.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
                        nil];

NSString *content = @"field1=42&field2=Hello";

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlStr]];
    [request setHTTPMethod:@"GET"];

    [request setHTTPBody:[content dataUsingEncoding:NSISOLatin1StringEncoding]];

    [NSURLConnection connectionWithRequest:request delegate:self];

    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];

    if (connection) {
        NSLog(@"good conection");

        [_receivedData appendData:_data];
        NSString *DataString = [[NSString alloc] initWithData:_receivedData encoding:NSUTF8StringEncoding];
        NSLog(@"foo1: %@", DataString);
        NSLog(@"foo2: %@", _receivedData);

    }

2014-01-03 22:27:57.322 App[962:70b] foo1: 
2014-01-03 22:27:57.323 App[962:70b] foo2: (null)

【问题讨论】:

  • 而 _data 来自哪里?您在 _receivedData 中的何处创建对象?在复制这段代码之前,您是否尝试过理解它?
  • 您应该阅读有关 NSURLConnection... 阅读此链接 codewithchris.com/…
  • 这段代码看起来很不完整。在发布问题之前,您应该对此进行更多研究。

标签: ios http get


【解决方案1】:

实现以下 NSURLConnection 委托以异步获取数据。

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    // A response has been received, this is where we initialize the instance var you created
   // so that we can append data to it in the didReceiveData method
   // Furthermore, this method is called each time there is a redirect so reinitializing it
   // also serves to clear it
   _responseData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    // Append the new data to the instance variable you declared
    [_responseData appendData:data];
}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
              willCacheResponse:(NSCachedURLResponse*)cachedResponse {
    // Return nil to indicate not necessary to store a cached response for this connection
    return nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // The request is complete and data has been received
    // You can parse the stuff in your instance variable now

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    // The request has failed for some reason!
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-19
    • 2015-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-03
    相关资源
    最近更新 更多