2015-01-11 7 views
1

CloudApp의 API (https://github.com/cloudapp/objective-c)를 사용하여 앱을 개발하려고합니다. 현재 사용자가 계정 세부 정보 (예 : 이메일, 구독 세부 정보 등)를 볼 수있는 곳으로 만들고 싶습니다. 그들의 API는 그런 종류의 일을하기 위해 제대로 작동하지 않지만 컬의 예는 완벽하게 작동합니다. 이 출력됩니다curl 문을 Objective-C로 변환

curl --digest -u [email protected]:trij2323 \ 
    -H "Accept: application/json" \ 
    "http://my.cl.ly/account" 

는 :

{"created_at":"2015-01-11T21:08:56Z","domain":null,"domain_home_page":null,"email":"[email protected]","id":1778166,"private_items":true,"updated_at":"2015-01-11T21:08:56Z","activated_at":"2015-01-11T21:08:56Z","subscribed":false,"socket":{"auth_url":"http://my.cl.ly/pusher/auth","api_key":"4f6dbc3b89fa4ee9a8ff","app_id":"4721","channels":{"items":"private-items_1778166"}},"subscription_expires_at":null} 

나는 가능한 한 컬 문만큼 뭔가를하고 싶었다. 나는 구글과 StackOverflow에 둘러 보았다이 답 (Objective-C equivalent of curl request) 발견 :

NSURL *url = [NSURL URLWithString: [NSString stringWithFormat:@"http://%@:%@@www.example.com/myapi/getdata", API_USERNAME, API_PASSWORD]]; 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 

[request setURL:url]; 
[request setHTTPMethod:@"GET"]; 
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 

NSError *error; 
NSURLResponse *response; 
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 

내가 약간 수정했다,하지만 :

NSString *apiUserName = [NSString stringWithFormat:@"[email protected]"]; 
NSString *apiPassword = [NSString stringWithFormat:@"trij2323"]; 

NSURL *url = [NSURL URLWithString: [NSString stringWithFormat:@"http://%@:%@@my.cl.ly/account", apiUserName, apiPassword]]; 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 

[request setURL:url]; 
[request setHTTPMethod:@"GET"]; 
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 

NSError *error; 
NSURLResponse *response; 
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 

NSLog(@"%@", data); 

을하지만 대신의 결과를 얻는 그것을 시도 할 때 터미널에서 문 말림, 나는 콘솔이있어 ...

<3c21646f 63747970 65206874 6d6c3e0a 0a3c6874 6d6c2078 6d6c6e73 3a6f673d 22687474 703a2f2f 6f70656e 67726170 6870726f 746f636f 6c2e6f72 672f7363 68656d61 2f222078 6d6c6e73 3a66623d 22687474 703a2f2f 7777772e 66616365 626f6f6b 2e636f6d 2f323030 382f6662 6d6c2220 6974656d 73636f70 65206974 656d7479 70653d22 68747470 3a2f2f73 6368656d 612e6f72 672f5468 696e6722 20636c61 73733d22 73717561 72657370 6163652d 64616d61 736b2220 6c616e67 3d22656e 2d434122 3e0a0a20 203c6865 61643e0a 20202020 0a202020 203c6d65 74612063 68617273 65743d22 7574662d 38223e0a 20202020 3c6d6574 61206874 74702d65 71756976 3d22582d 55412d43 6f6d7061 7469626c 65222063 6f6e7465 6e743d22 49453d65 6467652c 

61676522 297c7c68 61734174 74722861 5b625d2c 22646174 612d7372 63222929 26262266 616c7365 22213d3d 67657441 74747228 615b625d 2c226461 74612d6c 6f616422 292b2222 2626496d 6167654c 6f616465 722e6c6f 61642861 5b625d29 7d696e69 7428293b 77696e64 6f772e59 55492626 5955492e 61646428 22737175 61726573 70616365 2d696d61 67656c6f 61646572 222c6675 6e637469 6f6e2861 297b7d29 3b0a7d29 28293b3c 2f736372 6970743e 0a3c7363 72697074 3e537175 61726573 70616365 2e616674 6572426f 64794c6f 61642859 293b3c2f 73637269 70743e0a 0a0a2020 20200a20 203c2f62 6f64793e 0a0a3c2f 68746d6c 3e200a> 

(더 많은 것이 있지만 오래 가지 않을 것입니다. 정식 버전을 확인해야하는 경우 알려주세요.)

여기에서 무엇을해야할지 모르겠습니다. 이 문제를 해결하는 방법을 알고있는 사람이 있습니까? 미리 감사드립니다.

+2

' NSLog ("%의 @"@, 데이터) ; 사용'NSString * str = [[NSString alloc] initWithData : 데이터 인코딩 : NSUTF8StringEncoding]; NSLog (@ "% @", str); ' –

+0

데이터를 NSJSONSerialization에 전달해야합니다. - https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSJSONSerialization_Class/index.html – Paulw11

+0

CURL에서 표시된 텍스트는 JSON입니다. OP의 코멘트에서 그는 HTML을 얻는 동안 URL에 문제가있을 수 있지만 JSONSerialization은 궁극적으로 무엇이 필요할 것입니까? – Paulw11

답변

0

생각

  1. 귀하의 응답의 몇 HTML입니다 : 이것은 일반적으로 (그러나 HTML의 전체 텍스트를 보지 않고, 그것의 요청에 일부 문제가 있음을 의미

    <!doctype html> 
    
    <html xmlns:og="http://opengraphprotocol.org/schema/" xmlns:fb="http://www.facebook.com/2008/fbml" itemscope itemtype="http://schema.org/Thing" class="squarespace-damask" lang="en-CA"> 
    
        <head> 
    
        <meta charset="utf-8"> 
        <meta http-equiv="X-UA-Compatible" content="IE=edge, 
    
    ... 
    
    age")||hasAttr(a[b],"data-src"))&&"false"!==getAttr(a[b],"data-load")+""&&ImageLoader.load(a[b])}init();window.YUI&&YUI.add("squarespace-imageloader",function(a){}); 
    })();</script> 
    <script>Squarespace.afterBodyLoad(Y);</script> 
    
    
    
        </body> 
    
    </html> 
    

    정확히 무엇이 잘못되었는지 말하기는 어렵다.)

  2. 컬의 Accept 헤더를 application/json으로 지정했지만 Objective-C 예에서 Content-Type 헤더의 값을 사용했습니다. 요청은 JSON (이 경우에는 적어도)이 아니므로 Content-Type 헤더가 아닌 말글에서와 같이 Objective-C 코드에 Accept 헤더를 설정하려는 것으로 의심됩니다.

  3. 귀하의 컬 요청이 "다이제스트"인증을 지정했습니다. CloudApp의 설명서에는 다이제스트 인증이 사용된다고 나와 있습니다. 그러나 Objective-C 코드는 어떤 인증도하지 않습니다.

  4. 동기식 네트워크 요청을 수행하고 있습니다. 주 스레드에서 동기 요청을 수행하지 않으려 고합니다.

당신은 아마 NSURLSession를 사용하여 요청을 수행 할 (또는 7.0, NSURLConnection 이전의 iOS 버전을 지원해야하는 경우) 것이다. 이는 인증을 수행 할 수있는 지점 3과 4를 모두 해결하고 요청을 비동기 적으로 수행합니다.여전히 요청에 대한 완료 블록 패턴의 우아함을 즐기면서 예를 들어, NSURLSession, 당신은, 자신을 인증 위임 방법을 사용할 수 있습니다 :

대신
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler 
{ 
    if (challenge.previousFailureCount == 0) { 
     NSURLCredential *credential = [NSURLCredential credentialWithUser:self.userid password:self.password persistence:NSURLCredentialPersistenceForSession]; 
     completionHandler(NSURLSessionAuthChallengeUseCredential, credential); 
    } else { 
     completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil); 
    } 
} 

// you might have to implement the session rendition of the above authentication routine; it depends upon your server configuration; the implementation will look almost identical to the above code 
// 
// - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler 

- (void)performQuery { 
    // note, no user credentials in the URL; will be handled by authentication delegate method 
    NSURL *url = [NSURL URLWithString: @"http://www.example.com/myapi/getdata"]; 

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 
    [request setHTTPMethod:@"GET"]; 
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; 

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; 
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]]; 

    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
     if (!data) { 
      NSLog(@"dataTaskWithURL error: %@", error); 
      return; 
     } 

     NSError *parseError; 
     id responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError]; 
     if (responseObject) { 
      // got the JSON I was expecting; go ahead and use it; I'll just log it for now 
      NSLog(@"responseObject = %@", responseObject); 
     } else { 
      // if it wasn't JSON, it's probably some error, so it's sometimes useful to see what the HTML actually says 
      NSLog(@"responseString = %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); 
     } 
    }]; 
    [task resume]; 
} 
+0

그것을 시도했다. 그것은 내가 원하는 결과를 이끌어 냈습니다. 귀하의 도움에 감사 드리며 즉시 응답하지 않으신 것에 대해 사과드립니다. – chrisjr