#import "Twitter.h"
#import "StringUtil.h"
#define NETWORK_TIMEOUT 20.0
@implementation Twitter
@synthesize buf;
- (void)dealloc
{
[connection release];
[buf release];
[super dealloc];
}
- (void)post:(NSString*)options {
// NSString *username = [[options componentsSeparatedByString:@"::"] objectAtIndex:0];
// NSString *password = [[options componentsSeparatedByString:@"::"] objectAtIndex:1];
[connection release];
[buf release];
NSString *URL = (NSString*)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)@"http://twitter.com/statuses/update.json", (CFStringRef)@"%", NULL, kCFStringEncodingUTF8);
[URL autorelease];
NSMutableURLRequest* req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URL]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:NETWORK_TIMEOUT];
[req setHTTPMethod:@"POST"];
[req setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
NSString *username = [[NSUserDefaults standardUserDefaults] stringForKey:@"dirs"];
NSString *password = [[NSUserDefaults standardUserDefaults] stringForKey:@"xxx"];
NSString* auth = [NSString stringWithFormat:@"%@:%@", username, password];
NSString* basicauth = [NSString stringWithFormat:@"Basic %@", [NSString base64encode:auth]];
[req setValue:basicauth forHTTPHeaderField:@"Authorization"];
NSString *body = [NSString stringWithFormat:@"status=%@&source=iWake",
@"i just wake up"];
int contentLength = [body lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
[req setValue:[NSString stringWithFormat:@"%d", contentLength] forHTTPHeaderField:@"Content-Length"];
[req setHTTPBody:[NSData dataWithBytes:[body UTF8String] length:contentLength]];
buf = [[NSMutableData data] retain];
connection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
}
+ (void)update:(NSString*)options forWebView:(UIWebView*)webView {
[self post:options];
alert(@"a");
}
- (void)connection:(NSURLConnection *)aConnection didReceiveResponse:(NSURLResponse *)aResponse
{
NSHTTPURLResponse *resp = (NSHTTPURLResponse*)aResponse;
if (resp) {
alert(@"Response: %d", resp.statusCode);
}
[buf setLength:0];
}
- (void)connection:(NSURLConnection *)aConn didReceiveData:(NSData *)data
{
[buf appendData:data];
}
- (void)connection:(NSURLConnection *)aConn didFailWithError:(NSError *)error
{
[connection autorelease];
connection = nil;
[buf autorelease];
buf = nil;
NSString* msg = [NSString stringWithFormat:@"Error: %@ %@",
[error localizedDescription],
[[error userInfo] objectForKey:NSErrorFailingURLStringKey]];
alert(@"Connection failed: %@", msg);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)aConn
{
NSString* s = [[[NSString alloc] initWithData:buf encoding:NSUTF8StringEncoding] autorelease];
alert(s);
[connection autorelease];
connection = nil;
[buf autorelease];
buf = nil;
}
@end