13

小さな Twitter クライアントを実行しようとしていますが、認証が必要な API 呼び出しをテストしているときに問題が発生しました。

パスワードに特殊文字が含まれているため、次のコードを使用しようとしても機能しません。

NSString *post = [NSString stringWithFormat:@"status=%@", [status stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@:%@@%@/statuses/update.json", username, password, TwitterHostname]];
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

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

私はbase64を調べ始め、認証をヘッダーに入れました。base64 の実装に関するDave Dribin の投稿を見つけましたが、それは理にかなっているように思えました。しかし、私がそれを使おうとすると、コンパイラはopensslライブラリが見つからないという不平を言い始めました。そのため、libcrypto ライブラリにリンクする必要があることを読みましたが、iphone には存在しないようです。

また、アップルは暗号化ライブラリを使用するアプリを許可しないと言っている人を読んだことがありますが、これは私には理解できません。

だから今、私はちょっと立ち往生して混乱しています。アプリで基本認証を取得する最も簡単な方法は何ですか?

乾杯

4

2 に答える 2

15

2つのこと。まず、同期/クラス メソッドではなく、非同期メソッドを使用する必要があります。

NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:req]
                                                               cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                           timeoutInterval:30.0];

// create the connection with the request
// and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

認証は、デリゲートにこのメソッドを実装することによって管理されます。

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;

また、おそらくこれらのメソッドも実装する必要があります。

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;

いずれにせよ、非同期メソッドを使用すると、ユーザー エクスペリエンスが向上する傾向があるため、複雑さが増しますが、認証を行う機能がなくても実行する価値があります。

于 2009-06-14T18:27:14.643 に答える