SORU
16 Aralık 2010, PERŞEMBE


Nasıl Http isteği json veri NSURLRequest ile göndermek için

Objective-c yeniyim ve tepki olarak yeni/istek içine çaba büyük bir anlaşma koymak için başladım. Bir url (http üzerinden) arama ve json döndü ayrıştırabilir çalışan bir örnek var.

Bu çalışma örnek aşağıda

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [responseData setLength:0];
}

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

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
  NSLog([NSString stringWithFormat:@"Connection failed: %@", [error description]]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    [connection release];
  //do something with the json that comes back ... (the fun part)
}

- (void)viewDidLoad
{
  [self searchForStuff:@"iPhone"];
}

-(void)searchForStuff:(NSString *)text
{
  responseData = [[NSMutableData data] retain];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.whatever.com/json"]];
    [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

İlk sorum bu yaklaşım ölçek olacak? Veya zaman uyumsuz (uygulama yanıt beklerken UI iş parçacığı, g blok, anlamı bu

İkinci sorum - nasıl istek bu parçası bir POST yapmak yerine ALMAK için değiştirmek olabilir miyim? Sadece bu yüzden gibi HttpMethod değiştirmek için mi?

[request setHTTPMethod:@"POST"];

Ve son olarak - ne kadar basit bir dize (örneğin) bu mesaja json veri kümesi eklerim

{
    "magic":{
               "real":true
            },
    "options":{
               "happy":true,
                "joy":true,
                "joy2":true
              },
    "key":"123"
}

Şimdiden teşekkür ederim

CEVAP
17 Aralık 2010, Cuma


Burada JSON benim server olacak anahtar için bir değer (başka bir sözlük) = ile sözlük bir soru..yani {: = ^ soru olması gerek. (lütfen unutmayın ki yaptığım şey bu { sözlük } } ):

NSArray *objects = [NSArray arrayWithObjects:[[NSUserDefaults standardUserDefaults]valueForKey:@"StoreNickName"],
  [[UIDevice currentDevice] uniqueIdentifier], [dict objectForKey:@"user_question"],     nil];
NSArray *keys = [NSArray arrayWithObjects:@"nick_name", @"UDID", @"user_question", nil];
NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

NSDictionary *jsonDict = [NSDictionary dictionaryWithObject:questionDict forKey:@"question"];

NSString *jsonRequest = [jsonDict JSONRepresentation];

NSLog(@"jsonRequest is %@", jsonRequest);

NSURL *url = [NSURL URLWithString:@"https://xxxxxxx.com/questions"];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
             cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];


NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];

[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestData];

NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
 receivedData = [[NSMutableData data] retain];
}

Bu receivedData sonra idare tarafından

NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [jsonString JSONValue];
NSDictionary *question = [jsonDict objectForKey:@"question"];

Bu bile 0 net değil ve bazı yeniden okuma olacak, ama her şey başlamak için burada olmalı. Ve anladığım kadarıyla, bu zaman uyumsuz. Benim UI bu çağrılar yapılırken kilitli değil. Bu yardımcı olur umarım.

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • ElChakotay Andrich

    ElChakotay A

    10 EKİM 2013
  • Jana Williams

    Jana William

    17 AĞUSTOS 2011
  • Roger Huffman

    Roger Huffma

    4 ŞUBAT 2007