Posting user profile pic to twitter giving Error 131 - http

When trying to post a users profile pic to twitter, I am getting Error code 131 response back:
2013-12-06 19:17:29.854 Tweetly[8131:60b] {
errors = (
{
code = 131;
message = "Internal error";
}
);
}
Twitters website lists this:
"Corresponds with an HTTP 500 - An unknown internal error occurred."
Here is my code:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
//Code for store image
[picker dismissViewControllerAnimated:YES completion:nil];
UIImage *image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
UIImage *scaledImage = [self imageWithImage:image convertToSize:CGSizeMake(500, 500)];
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(scaledImage)];
[self uploadPictureWithData:imageData];
}
- (UIImage *)imageWithImage:(UIImage *)image convertToSize:(CGSize)size {
UIGraphicsBeginImageContext(size);
[image drawInRect:CGRectMake(0, 0, size.width, size.height)];
UIImage *destImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return destImage;
}
- (void)uploadPictureWithData:(NSData *)imageData {
// Get the twitter feed
NSURL *requestURL = [NSURL URLWithString:#"https://api.twitter.com/1.1/account/update_profile_image.json"];
// Set up proper parameters
NSMutableDictionary *timelineParameters = [[NSMutableDictionary alloc] init];
[timelineParameters setObject:imageData forKey:#"image"];
[timelineParameters setObject:#"1" forKey:#"skip_status"];
// Create the Social Request
SLRequest *postRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodPOST URL:requestURL parameters:timelineParameters];
postRequest.account = self.delegate.userAccount;
// Perform the request
[postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
// Check if we reached the reate limit
if ([urlResponse statusCode] == 429) {
// Rate limit reached
// Display an alert letting the user know we have hit the rate limit
UIAlertView *twitterAlert = [[UIAlertView alloc] initWithTitle:kRateLimitTitle
message:kRateLimitMessage
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[twitterAlert show];
return;
}
// Check if there was an error
if (error) {
NSLog(#"Error: %#", error.localizedDescription);
return;
}
// Check if there is some response data
if (responseData) {
NSError *jsonError = nil;
NSMutableArray *feedData = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&jsonError];
if (!jsonError) {
// Check the response data
NSLog(#"%#", feedData);
} else {
// Alert the user with the error
UIAlertView *twitterAlert = [[UIAlertView alloc] initWithTitle:kErrorTitle
message:kErrorMessage
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[twitterAlert show];
}
} else {
// Alert the user with the error
UIAlertView *twitterAlert = [[UIAlertView alloc] initWithTitle:kErrorTitle
message:kErrorMessage
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[twitterAlert show];
}
});
}];
}
Any idea what the issue might be? I initially thought it was because the image was too big, so I added the method for scaling the image down to 500 x 500, but I get the same error.
This error happens while running on both the device and the simulator.
Does anyone see where the problem is or have any extra insight? Thanks!

In my tests, images larger than 1000x1000px are not downscaled synchronously, throwing the 131 response code. Undocumented, unfortunately.
Make sure the image is <700kb and smaller than 1000x1000px.
https://dev.twitter.com/rest/reference/post/account/update_profile_image

Related

How to get a video PHAsset disk file size?

I'm trying to determine the file size on disk of a PHAsset video.
The following code is returning am error "The file “IMG_0188.mov” couldn’t be opened because you don’t have permission to view it."
PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
options.version = PHVideoRequestOptionsVersionOriginal;
[[PHImageManager defaultManager] requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset *avAsset, AVAudioMix *audioMix, NSDictionary *info) {
videoURL = [(AVURLAsset*)avAsset URL];
NSNumber *videoDiskFileSize;
NSError *error;
[videoURL getResourceValue:&videoDiskFileSize forKey:NSURLFileSizeKey error:&error];
if(error){
NSLog(#"ERROR %#", error.localizedDescription);
}
NSLog(#"size is %f",[videoDiskFileSize floatValue]/(1024.0*1024.0));
}];
Here's the correct way to do it.
PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
options.version = PHVideoRequestOptionsVersionOriginal;
[[PHImageManager defaultManager] requestExportSessionForVideo:asset options:options exportPreset:AVAssetExportPresetHighestQuality resultHandler:^(AVAssetExportSession *exportSession, NSDictionary *info) {
CMTime videoDuration = CMTimeMultiplyByFloat64(exportSession.asset.duration, 1);
exportSession.timeRange = CMTimeRangeMake(kCMTimeZero, videoDuration);
NSLog(#"Byyte size = %lld", exportSession.estimatedOutputFileLength);
videoSize = exportSession.estimatedOutputFileLength;
}];

Audio playing not working when ios device is locked

I am doing the following things to make audio play when an iOS device is locked, but it doesn't work.
UIBackgroundModes key (with the value audio) in Info.plist file.
set up audio session
code:
- (void)viewDidLoad
{
[super viewDidLoad];
[self createAudioSession];
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"jgj" ofType:#"mp3"];
NSURL *url = [NSURL fileURLWithPath:soundFilePath];
NSLog(#"%#",[url path]);
NSError* error;
self.audioPlayer=[[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
if (self.audioPlayer == nil)
NSLog(#"%#",[error description]);
else
{
self.audioPlayer.numberOfLoops=-1;
[self.audioPlayer play];
}
}
-(void)createAudioSession
{
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
// Use this code to allow the app sound to continue to play when the screen is locked.
NSError* error=nil;
BOOL ok=[audioSession setCategory: AVAudioSessionCategoryPlayback error: &error];
if(!ok)
NSLog(#"%#",[error description]);
else
NSLog(#"hello");
ok=[audioSession setActive:YES error:&error];
if(!ok)
NSLog(#"%#",[error description]);
else
NSLog(#"world");
}

ZUUIRevealController - Memory allocations keeps on increasing & slow UIAlertView & UIActionsheet

I am starting with new iOS app in which I have to use Reveal control. So I planned to use great ZUUIRevealController library. I just created UI for 2 - 3 screens . In one of those screen I have to shown UIAlertView & UIActionsheet. But I realised that UIAlertView & UIActionsheet shows very slowly (it adds black overlay first & then shows UIAlertView/UIActionsheet, kind of alert view hangs while showing. Animation is not smooth). I didn't added any logic for coding just created the UI. I didn't use any background thread / dispatch_asyn(). So there is no issue of updating UI from background thread. So I checked the memory leaks & allocations. I didn't see any memory leaks , but memory allocations keeps on increasing while I reveal the menu & push new view controller. It doesn't decrese when I pop the view controller. Here are the screenshots :
1) When app launches
2) After some time , when I push new view controller, pop view controller
I know ZUUIRevealController library creates new instance of view controller every time I select a row from Menu. So I crated the instance variables of view controllers in .h file , but still I have same problem.
Here is my code
// AppDelegate.m
// On SplashViewController , I decide whether to show menu or Login screen
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.splashViewController = [[SplashViewController alloc]initWithNibName:#"SplashViewController" bundle:nil];
self.window.rootViewController = self.splashViewController;
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
[self customizeUIControlsAppearance];
return YES;
}
// SplashViewController.m
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
BOOL isLoggedIn = YES;
if(isLoggedIn){
[self showMenuViewController];
}
else{
[self showStartUpViewController];
}
}
-(void)showStartUpViewController
{
StartUpViewController *startUpViewController = [[StartUpViewController alloc]initWithNibName:#"StartUpViewController" bundle:nil];
UINavigationController *navController=[[UINavigationController alloc] initWithRootViewController:startUpViewController];
[self presentViewController:navController animated:NO completion:^{
}];
}
-(void)showMenuViewController
{
MenuViewController *menuViewController=[[MenuViewController alloc] init];
CategoryViewController *categoryViewController=[[CategoryViewController alloc]initWithNibName:#"CategoryViewController" bundle:nil];
categoryViewController.isViewControllerShownFromMenu = YES;
UINavigationController *navController=[[UINavigationController alloc] initWithRootViewController:categoryViewController];
RevealController *revealController=[[RevealController alloc] initWithFrontViewController:navController rearViewController:menuViewController];
[self presentViewController:revealController animated:NO completion:^{
}];
}
// MenuViewController.m
// SettingsViewController & NewsViewController are decalred in .h file with property & syntheszie
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
RevealController *revealController = [self.parentViewController isKindOfClass:[RevealController class]] ? (RevealController *)self.parentViewController : nil;
// Switch using Section Number
switch (indexPath.section) {
case OTHER_SECTION:
switch (indexPath.row) {
case NEWS:
[self showNewsViewControllerUsingRevealController:revealController];
break;
case SETTINGS:
[self showSettingsViewControllerUsingRevealController:revealController];
break;
default:
break;
}
break;
default:
break;
}
}
#pragma mark - Show News & Settings View Controllers
-(void)showNewsViewControllerUsingRevealController:(RevealController*)revealController
{
if ([revealController.frontViewController isKindOfClass:[UINavigationController class]] && ![((UINavigationController *)revealController.frontViewController).topViewController isKindOfClass:[NewsViewController class]])
{
if(!self.newsViewController)
self.newsViewController = [[NewsViewController alloc] initWithNibName:#"NewsViewController" bundle:nil];
self.newsViewController.isViewControllerShownFromMenu = YES;
UINavigationController *navigationController= [[UINavigationController alloc] initWithRootViewController:self.newsViewController];
[revealController setFrontViewController:navigationController animated:NO];
}
else
{
[revealController revealToggle:self];
}
}
-(void)showSettingsViewControllerUsingRevealController:(RevealController*)revealController
{
if ([revealController.frontViewController isKindOfClass:[UINavigationController class]] && ![((UINavigationController *)revealController.frontViewController).topViewController isKindOfClass:[SettingsViewController class]])
{
if(!self.settingsViewController)
self.settingsViewController= [[SettingsViewController alloc] initWithNibName:#"SettingsViewController" bundle:nil];
self.settingsViewController.isViewControllerShownFromMenu = YES;
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:self.settingsViewController];
[revealController setFrontViewController:navigationController animated:NO];
}
else
{
[revealController revealToggle:self];
}
}
// Code for shwoing UIAlertView & UIActionsheet
-(void)showAlertWithTitle:(NSString*)title andMessage:(NSString*)message
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:title message:message delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
-(void)btnInviteTapped:(id)sender event:(UIEvent*)event
{
UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:NSLocalizedString(#"FRIENDS_VC:INVIT_ACTIONSHEET_TITLE", nil) delegate:self cancelButtonTitle:NSLocalizedString(#"FRIENDS_VC:ACTIONSHEET_CANCEL_BUTTON",nil) destructiveButtonTitle:nil otherButtonTitles:NSLocalizedString(#"FRIENDS_VC:ACTIONSHEET_SMS_BUTTON",nil),NSLocalizedString(#"FRIENDS_VC:ACTIONSHEET_EMAIL_BUTTON",nil), nil];
actionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
[actionSheet showInView:self.view];
}
By the way I have 11 menu items.
My Login & Regsiter flow is not embedded in MenuViewController. On Login & REgsiter , UIAlertView & UIActionSheet shows smoothly.
Any idea whats going wrong here ? Did I make some mistake in coding ?
Why my UIAlertView & UIActionsheet are not showing smoothly ?
Any kind of help is appreciated. Thanks.

iOS: How to perform NSURLConnection and get repsonse before continuing?

I'm trying to get updates from my server. I want it to have the latest information though so I'm running a page and if the response is "Complete" and not "Error" then I will proceed with the Update methods to get the latest information from the xml file. My problem is the Delegate methods are not getting called until all my code in my "Main" function is completed. By that time the code has already gone past my if statement checking if the responseSuccess is TRUE or FALSE. I think its because the NSURLConnection is asynchronous... yet im not sure how to fix it. If I need to provide more code/information just let me know. Thanks!
Main
if (UpdatingFlag)
{
NSLog(#"Cannot update while updating is in process...");
} else {
// run updates before getting information
[self getResponse:#"http://url/path/to/file?function=myvalue"];
[self setBottomBarToUpdating:#"Processing Please Wait..."];
dispatch_queue_t queue = dispatch_queue_create("updateQueue", DISPATCH_QUEUE_CONCURRENT);
UpdatingFlag = TRUE;
if(responseSuccess)
{
dispatch_async(dispatch_get_main_queue(),^ {
[self setBottomBarToUpdating:#"Updating..."];
[self updateFromXMLFile:#"https://url/path/to/file.xml"];
});
}
UpdatingFlag = FALSE;
dispatch_barrier_async(queue,^ {
dispatch_async(dispatch_get_main_queue(), ^{
[self setBottomBarToUpdated];
});
});
}
GetReponse Method
- (void) getResponse:(NSString *)url
{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:45.0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
if (connection) {NSLog(#"Connecting...");
} else {NSLog(#"Didn't Connect Error...");}
}
Delegate Methods
#pragma mark NSURLConnection methods
- (void)connection:(NSURLConnection *)conn didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
NSLog(#"Did Receive Challenge");
if ([challenge previousFailureCount] == 0) {
NSURLCredential *newCredential;
newCredential = [NSURLCredential credentialWithUser:#"user" password:#"pass" persistence:NSURLCredentialPersistenceNone];
[[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
} else {
[[challenge sender] cancelAuthenticationChallenge:challenge];
NSLog(#"Invalid Username and Password");
UIAlertView * userNameAlert = [[UIAlertView alloc]initWithTitle:#"Error"
message:#"ErrorMsg"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"OK", nil];
[userNameAlert show];
}
}
- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data {
NSLog(#"Received Data Packet...");
response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"Error, %#", error);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)conn {
NSLog(#"Finished Loading");
if([response rangeOfString:#"Complete"].location == NSNotFound) {
// success
responseSuccess = FALSE;
} else {
// failed
responseSuccess = TRUE;
}
}
- (BOOL)connection:(NSURLConnection *)conn canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
return YES;
}
Any code you want to run after the you get the update from your server needs to be moved to (or called from) the connectionDidFinishLoading: method. So, you can get rid of the flags, and only have the getResponse call in your main code.

i had some images in resultstring i want to display it in tableview

i had some images in resultstring ,resultstring is what i get from the server ,it contains images ,i want that images and display it in tableview
my code is
viewdidload
{
NSString *urlVal = #"http://at.azinova.info/green4care/iphone/viewImage.php?id=";
NSString *urlVal1 = [urlVal stringByAppendingString:selectedCountryw];
NSURL *url1 = [NSURL URLWithString:urlVal1];
//NSURL *url1 = [NSURL URLWithString:urlVal];
NSString *resultString = [NSString stringWithContentsOfURL:url1 encoding:NSUTF8StringEncoding error:nil];
NSArray *arycountries1 = [resultString componentsSeparatedByString:#","];
UIAlertView *loginalert = [[UIAlertView alloc] initWithTitle:#" Message" message:resultString delegate:self
cancelButtonTitle:#"OK" otherButtonTitles:nil];
[loginalert show];
[loginalert release];
//arraycountries = [[NSArray alloc]initWitho:arycountries1];
arraycountries = [[NSArray alloc]initWithArray: arycountries1];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [arraycountries count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.imageView.image = [UIImage imageNamed:[arraycountries objectAtIndex:indexPath.row]];
// Configure the cell...
return cell;
}
please help
thankzzzzz
What you described is much like a message borad with images, there is a twitter open source project tweetero: http://code.google.com/p/tweetero/ You can take a look at MessageListController and ImageLoader.
In generally, you could do like this:
1) Send async request to server to get message date(not images)
2) reload the table data, and send the image loader request for each uiimageview.
3) set the uiimageview when the image is loaded. A default loading image can be used until the real image is loaded.

Resources