Skip to content →

Three20: Uploading an image to a server

Here’s an example to upload an image (or any data file) to a server:


– (void) uploadMediaForUserId: (NSString*) userId {
NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithObjectsAndKeys:
kAPIVersion, @"v",
nil];
// Media Name
if( TTIsStringWithAnyText(_mediaName)){
[parameters setObject:_mediaName forKey:@"n"];
}

// Media Description
if( TTIsStringWithAnyText(_mediaDescription)){
[parameters setObject:_mediaDescription forKey:@"d"];
}

// REST resource, where kMedia: @"/users/%@/media";
NSString *resource = [NSString stringWithFormat:kMedia, userId];

// Create the URL, where kServerURL is something like "http://www.dougdiego.com"
NSString *url = [kServerURL stringByAppendingFormat:@"%@?%@", resource, [parameters gtm_httpArgumentsString]];
// Resulting URL looks like: http://www.dougdiego.com/users/12345/media

TTURLRequest* request = [TTURLRequest requestWithURL:url delegate:self];
request.httpMethod = @"POST";

NSString * imageLocalUrl = [NSString stringWithFormat:@"documents://%@",_mediaFilename];
NSData *imageData = UIImageJPEGRepresentation(TTIMAGE(imageLocalUrl), 0.6);

// Set the media file with the parameter: file
[request addFile:imageData mimeType:@"image/jpeg" fileName:@"file"];

request.cachePolicy = TTURLRequestCachePolicyNoCache;
request.cacheExpirationAge = TT_CACHE_EXPIRATION_AGE_NEVER;

TTURLJSONResponse* response = [[TTURLJSONResponse alloc] init];
request.response = response;
TT_RELEASE_SAFELY(response);

[request send];
}

Published in Apple Code iOS Three20