Shortening a URL containing & parameters - bit.ly

i have this URL and I am trying to shorten it through bit.ly API. Here is my code
NSString *url = #"http://www.example.com&username=abc&password=123&mode=offline";
NSString *requestStr = [NSString stringWithFormat:#"http://api.bit.ly/v3/shorten?login=%#&apiKey=%#&longUrl=%#&format=txt",login, api_key, url];
requestStr = [requestStr stringByReplacingOccurrencesOfString:#"&" withString:#"&"];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:requestStr]];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *response = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
I am getting a url in response which corresponds to only http://www.example.com
Surprisingly, &username=abc&password=123&mode=offline parts of the url are trimmed.
This happens only when I am doing it through xcode. On the website, it is working properly. PLease help.

NSString *url = #"https://www.googleapis.com/urlshortener/v1/url?key=UR_KEY";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:#"UR_LONG_URL",#"longUrl", nil];
[request setHTTPBody:[[dict JSONRepresentation] dataUsingEncoding:NSUTF8StringEncoding]];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *response = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

Related

PHImageManager.default().requestAVAsset for video

i have an big problem with my situation
my main problem is i need fetch video one by one do some operation on the video name and save it to the file system and again fetch another video do some operation on the video name and save it to the file system through the loop of asset the problem is completion handler prevent me do that because it saving all videos together without i do any editing and changing the name this save all videos i think it is working on background thread please any help to fix this problem i need handle fetch video one by one
this is my code
for asset in arrayOfAssets {
if asset.mediaType == .video {
PHImageManager.default().requestAVAsset(forVideo: asset, options: nil, resultHandler: { (AVAsset, AVAudio, info) in
// i need access to this place so i can fetch the video one by one and working with the AVAsset
})
}else{
let imageOp = PHImageRequestOptions()
PHImageManager.default().requestImage(for: asset, targetSize: CGSize(width:125,height:125), contentMode: .aspectFit, options: imageOp, resultHandler: { (img, info) in
print(img!)
})
}
}
i think this one is related to your query
for Vedios
How Can i Get the List of all Video files from Library in ios sdk
for Images
Get all of the pictures from an iPhone photoLibrary in an array using AssetsLibrary framework?
allVideos = [[NSMutableArray alloc] init];
ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];
[assetLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop)
{
if (group)
{
[group setAssetsFilter:[ALAssetsFilter allVideos]];
[group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop)
{
if (asset)
{
dic = [[NSMutableDictionary alloc] init];
ALAssetRepresentation *defaultRepresentation = [asset defaultRepresentation];
NSString *uti = [defaultRepresentation UTI];
NSURL *videoURL = [[asset valueForProperty:ALAssetPropertyURLs] valueForKey:uti];
NSString *title = [NSString stringWithFormat:#"video %d", arc4random()%100];
UIImage *image = [self imageFromVideoURL:videoURL];
[dic setValue:image forKey:#"image"];
[dic setValue:title forKey:#"name"];
[dic setValue:videoURL forKey:#"url"];
[`allVideos` addObject:dic];
}
}];
else
{
}
}
failureBlock:^(NSError *error)
{
NSLog(#"error enumerating AssetLibrary groups %#\n", error);
}];
--------for ALL PHOTOS
NSArray *imageArray;
NSMutableArray *mutableArray;
-(void)getAllPhotosFromCamera
{
imageArray=[[NSArray alloc] init];
mutableArray =[[NSMutableArray alloc]init];
PHImageRequestOptions *requestOptions = [[PHImageRequestOptions alloc] init];
requestOptions.resizeMode = PHImageRequestOptionsResizeModeExact;
requestOptions.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
requestOptions.synchronous = true;
PHFetchResult *result = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:nil];
NSLog(#"%d",(int)result.count);
PHImageManager *manager = [PHImageManager defaultManager];
NSMutableArray *images = [NSMutableArray arrayWithCapacity:[result count]];
// assets contains PHAsset objects.
__block UIImage *ima;
for (PHAsset *asset in result) {
// Do something with the asset
[manager requestImageForAsset:asset
targetSize:PHImageManagerMaximumSize
contentMode:PHImageContentModeDefault
options:requestOptions
resultHandler:^void(UIImage *image, NSDictionary *info) {
ima = image;
[images addObject:ima];
}];
}
imageArray = [images copy]; // You can direct use NSMutuable Array images
}

Change FBSession with page access token to publish post on fb page as admin

I want to publish a post as admin in a facebook page where the user is admin of the page.
I have the page access token from
[FBRequestConnection startWithGraphPath:#"/me/accounts"
parameters:nil
HTTPMethod:#"GET"
completionHandler:^(
FBRequestConnection *connection,
id result,
NSError *error
) {
NSString *token = [[[result objectForKey:#"data"] objectAtIndex:0] objectForKey:#"access_token"];//accessToken of the page
}];
Now how can i change the FBSession with this token to publish a post on the page as an admin using GraphAPI? FBDocumentation refers to this for openFromAccessTokenData . Please help as i m stuck with this for long time. I m using facebook sdk 3.2. Thanks in advance
NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:token, #"access_token",
titleCell.titleTextView.text,#"message",
[UserDefaultsManager fbPlaceId], #"place",
// fbPhotoId,#"object_attachment",
#"https://www.google.com",#"link",
photoUrl,#"picture",
titleCell.titleTextView.text,#"name",
typeCell.cellTextField.text,#"caption",
descriptionCell.descriptionTextView.text,#"description",
nil];
FBRequest *requestToPost = [[FBRequest alloc] initWithSession:nil
graphPath:#"/me/feed"
parameters:param
HTTPMethod:#"POST"];
FBRequestConnection *requestToPostConnection = [[FBRequestConnection alloc] init];
[requestToPostConnection addRequest:requestToPost completionHandler:^(FBRequestConnection *connection, id result, NSError *error){
if(!error)
{
NSLog(#"facebook result >> %#", result);
NSData *photoData = UIImagePNGRepresentation(promoImage);
NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:token,#"access_token",
photoData,#"source", nil];
FBRequest *requestToPostPhoto = [[FBRequest alloc] initWithSession:nil
graphPath:#"/me/photos"
parameters:param
HTTPMethod:#"POST"];
FBRequestConnection *requestToPostPhotoConnection = [[FBRequestConnection alloc] init];
[requestToPostPhotoConnection addRequest:requestToPostPhoto completionHandler:^(FBRequestConnection *connection, id result, NSError *error){
if(!error)
{
[loadingAlert dismissWithClickedButtonIndex:0 animated:YES];
NSLog(#"facebook result photo>> %#", result);
doneAlert = [[UIAlertView alloc] initWithTitle:#"Success"
message:#""
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
if(self.isUpdatingPromo)
{
doneAlert.message = #"Promo updated successfully";
[doneAlert show];
}
else
{
doneAlert.message = #"Promo created successfully";
[doneAlert show];
}
}
else
{
[loadingAlert dismissWithClickedButtonIndex:0 animated:YES];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Could not post photo"
delegate:nil
cancelButtonTitle:#"Dismiss"
otherButtonTitles:nil];
[alert show];
}
}];
[requestToPostPhotoConnection start];
}
else
{
[loadingAlert dismissWithClickedButtonIndex:0 animated:YES];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Could not post"
delegate:nil
cancelButtonTitle:#"Dismiss"
otherButtonTitles:nil];
[alert show];
}
}];
[requestToPostConnection start];

how to display ad banner (buzzcity) in cocos2d project?

is there a way to put UIView by converting it to EAGLView or should i have to add CAlayer ?
whats the best way to do it?
any Example codes related to BuzzCity for Cocos2d would be nice
what i have found till now----
btnAD = [CCMenuItemImage itemFromNormalImage:#"underwater-images-paradox-visual-wallpapers-title-search-196522.jpg" selectedImage:#"underwater-images-paradox-visual-wallpapers-title-search-196522.jpg" target:self selector:#selector(AdbuttonAction)];
btnAD.position=ccp(0, 0);
what i am trying is to display ad on button image...
and call the url for ad on buttonAction
how to display this button on top of my uiview?
documentation of buzzCity ad integration
http://docs.buzzcity.net/wiki/IOS_SDK#Advanced_Integration_using_BuzzCity_iOS_SDK
you can not sandwich UIViews between two cocos nodes. If you want an ad button, display the ad as background of a UIButton, or simply make the ad "touchable" by testing if touch location is within ad's frame.
first i saved my image to documents directory
- (NSString *)saveImage {
NSURL *url = [NSURL URLWithString:#"http://ads.buzzcity.net/show.php?partnerid=8404&browser=app_apple"];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
//convert image into .png format.
NSData *imageData = UIImagePNGRepresentation(image);
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:#"myImage"];
[imageData writeToFile:fullPath atomically:YES];
NSLog(#"image saved");
return fullPath;
}
then i added that path to **itemFromNormalImage:fullPath**
NSString *fullPath=[self saveImage];
btnAD = [CCMenuItemImage itemFromNormalImage:fullPath selectedImage:fullPath target:self selector:#selector(AdButtonAction)];
NSLog(#"btnAD %#", btnAD);
CCMenu *adMenu = [CCMenu menuWithItems:btnAD, nil];
[self addChild:adMenu];
adMenu.position = ccp(350 ,size.height-50);
finally on button action open the url
-(void)AdButtonAction
{
NSURL *url = [NSURL URLWithString:#"http://click.buzzcity.net/click.php?partnerid=8404&browser=app_apple"];
NSLog(#"url = %#",url);
[[UIApplication sharedApplication] openURL:url];
}

obj-c return block NSString to c++ after request

I'm trying to get this data correctly back to c++, but there are some random crashes. I want to access the data in C++. Sometimes it does, sometime it doesn't. I couldn't find a clear example on how to return this data. Here's my code:
- (NSString*) sendRequestToServer : (CLLocationCoordinate2D) location {
NSLog(#"getting geo from server %# %# ", [NSString stringWithFormat:#"%f", location.latitude],[NSString stringWithFormat:#"%f", location.longitude]);
__block long returnBytesSend = 0;
__block long returnBytesTotal = 0;
__block NSString* tempData = #"" ;
__block BOOL foundNow = false;
self.data = nil;
for (NXOAuth2Account *account in [[NXOAuth2AccountStore sharedStore] accounts]) {
NSMutableDictionary *params = [NSMutableDictionary dictionary];
[params setObject: [NSString stringWithFormat:#"%f", location.latitude] forKey: #"latitude"];
[params setObject: [NSString stringWithFormat:#"%f", location.longitude] forKey:#"longitude" ];
[params setObject: #"10" forKey: #"radius" ];
[params setObject: #"5" forKey: #"limit"];
NXOAuth2Client *client = [account oauthClient];
NXOAuth2AccessToken *tokenData = [client accessToken];
NSString * clientAccessToken = [tokenData accessToken];
NSString * clientRefreshToken = [tokenData refreshToken];
if (clientAccessToken && clientRefreshToken ){
[NXOAuth2Request performMethod:#"GET"
onResource:[NSURL URLWithString:#"http://www.server.com/list"]
usingParameters: params
withAccount:account
sendProgressHandler:^(unsigned long long bytesSend, unsigned long long bytesTotal) {
returnBytesSend = bytesSend ;
returnBytesTotal = bytesTotal;
}
responseHandler:^(NSURLResponse *response, NSData *responseData2, NSError *error){
NSLog(#"FOUND DATA");
NSRange range = [[[NSString alloc] initWithData:responseData2 encoding:NSUTF8StringEncoding] rangeOfString : #"facebook_id"];
if(range.location != NSNotFound) {
tempData = [[[NSString alloc] initWithData:responseData2 encoding:NSUTF8StringEncoding]retain];
//NSLog(#"%#", tempData);
self.data = [[tempData copy] autorelease];
foundData = true;
}
}];
}
}
return tempData;
}
I was trying to acces the data this way:
#interface oAuthView : UIWebView
#property (nonatomic, strong) __block NSString* data;
#property (nonatomic) __block BOOL foundData;
and in c++ like this:
oAuthView *getWebView;
getWebView =[[oAuthView alloc] initWithFrame:CGRectMake(10,40,300,400)];
if ([getWebView foundData] )
string dataS = string([[artPartView data] UTF8String]));

Is there a quick way to POST an NSDictionary to a Python/Django server?

I'm looking to send an NSDictionary up to a server running Django, and I would prefer if I had to do little or no work writing an encoder/parser.
Is there an easy way to accomplish this task?
iOS 5 has support for it in the framework. Look at NSJSONSerialization. Here is example code for post. Request object creation has been omitted in the code below.
NSDictionary *postDict = [NSDictionary dictionaryWithObjectsAndKeys:[NSDictionary dictionaryWithObjectsAndKeys:API_KEY, #"apiKey", userName, #"loginUserName", hashPassword, #"hashPassword", nil], #"loginReq", nil];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"content-type"];
NSError *error = nil;
[request setHTTPBody:[NSJSONSerialization dataWithJSONObject:postDict options:0 error:&error]];
iOS doesn't have support to do this as a one-liner, but you could do this:
#interface NSString (URLEncoding)
- (NSString *)urlEncodedUTF8String;
#end
#interface NSURLRequest (DictionaryPost)
+ (NSURLRequest *)postRequestWithURL:(NSURL *)url
parameters:(NSDictionary *)parameters;
#end
#implementation NSString (URLEncoding)
- (NSString *)urlEncodedUTF8String {
return (id)CFURLCreateStringByAddingPercentEscapes(0, (CFStringRef)self, 0,
(CFStringRef)#";/?:#&=$+{}<>,", kCFStringEncodingUTF8);
}
#end
#implementation NSURLRequest (DictionaryPost)
+ (NSURLRequest *)postRequestWithURL:(NSURL *)url
parameters:(NSDictionary *)parameters {
NSMutableString *body = [NSMutableString string];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request addValue:#"application/x-www-form-urlencoded"
forHTTPHeaderField:#"Content-Type"];
for (NSString *key in parameters) {
NSString *val = [parameters objectForKey:key];
if ([body length])
[body appendString:#"&"];
[body appendFormat:#"%#=%#", [[key description] urlEncodedUTF8String],
[[val description] urlEncodedUTF8String]];
}
[request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
return request;
}
#end
Then it's as simple as:
NSURL *url = [NSURL URLWithString:#"http://posttestserver.com/post.php"];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:42], #"number",
#"apple", #"brand", nil];
NSURLRequest *request = [NSURLRequest postRequestWithURL:url parameters:params];
[NSURLConnection sendAsynchronousRequest:request queue:nil completionHandler:nil];
Please note that in this example we're not caring about the response. If you care about it, supply a block so you can do something with it.