NSString *authLink = [NSString stringWithFormat:@"http://api.vk.com/oauth/authorize?client_id=%@&scope=wall,photos&redirect_uri=http://api.vk.com/blank.html&display=touch&response_type=token", appID]; NSURL *url = [NSURL URLWithString:authLink]; [vkWebView loadRequest:[NSURLRequest requestWithURL:url]];
-(void)webViewDidFinishLoad:(UIWebView *)webView { // if ([vkWebView.request.URL.absoluteString rangeOfString:@"access_token"].location != NSNotFound) { NSString *accessToken = [self stringBetweenString:@"access_token=" andString:@"&" innerString:[[[webView request] URL] absoluteString]]; // id , NSArray *userAr = [[[[webView request] URL] absoluteString] componentsSeparatedByString:@"&user_id="]; NSString *user_id = [userAr lastObject]; NSLog(@"User id: %@", user_id); if(user_id){ [[NSUserDefaults standardUserDefaults] setObject:user_id forKey:@"VKAccessUserId"]; } if(accessToken){ [[NSUserDefaults standardUserDefaults] setObject:accessToken forKey:@"VKAccessToken"]; // . expires_in=86400 , . // , , [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"VKAccessTokenDate"]; [[NSUserDefaults standardUserDefaults] synchronize]; } NSLog(@"vkWebView response: %@",[[[webView request] URL] absoluteString]); [(ViewController *)delegate authComplete]; [self dismissModalViewControllerAnimated:YES]; } else if ([vkWebView.request.URL.absoluteString rangeOfString:@"error"].location != NSNotFound) { NSLog(@"Error: %@", vkWebView.request.URL.absoluteString); [self dismissModalViewControllerAnimated:YES]; } }
[(ViewController *)delegate authComplete]; [self dismissModalViewControllerAnimated:YES];
- (void) sendText { NSString *user_id = [[NSUserDefaults standardUserDefaults] objectForKey:@"VKAccessUserId"]; NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"VKAccessToken"]; NSString *text = @" API !"; // NSString *sendTextMessage = [NSString stringWithFormat:@"https://api.vk.com/method/wall.post?owner_id=%@&access_token=%@&message=%@", user_id, accessToken, [self URLEncodedString:text]]; NSLog(@"sendTextMessage: %@", sendTextMessage); // NSDictionary *result = [self sendRequest:sendTextMessage withCaptcha:NO]; // NSString *errorMsg = [[result objectForKey:@"error"] objectForKey:@"error_msg"]; if(errorMsg) { [self sendFailedWithError:errorMsg]; } else { [self sendSuccessWithMessage:@" !"]; } }
// - (NSString *)URLEncodedString:(NSString *)str { NSString *result = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)str, NULL, CFSTR("!*'();:@&=+$,/?%#[]"), kCFStringEncodingUTF8); [result autorelease]; return result; }
[self sendRequest:sendTextAndLinkMessage withCaptcha:NO];
As you can see, the function accepts the withCaptcha: (BOOL) parameter, which we will need if the server requests a user to enter a captcha to confirm actions. Since no captcha is required for the time being, we transmit NO.
- (NSDictionary *) sendRequest:(NSString *)reqURl withCaptcha:(BOOL)captcha { // , captcha_sid captcha_key if(captcha == YES){ NSString *captcha_sid = [[NSUserDefaults standardUserDefaults] objectForKey:@"captcha_sid"]; NSString *captcha_user = [[NSUserDefaults standardUserDefaults] objectForKey:@"captcha_user"]; // . , . reqURl = [reqURl stringByAppendingFormat:@"&captcha_sid=%@&captcha_key=%@", captcha_sid, [self URLEncodedString: captcha_user]]; } NSLog(@"Sending request: %@", reqURl); NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:reqURl] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0]; // NSURLConnection, NSData NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; // , JSONKit NSDictionary if(responseData){ NSDictionary *dict = [[JSONDecoder decoder] parseJSONData:responseData]; // NSString *errorMsg = [[dict objectForKey:@"error"] objectForKey:@"error_msg"]; NSLog(@"Server response: %@ \nError: %@", dict, errorMsg); // . Captcha needed, . if([errorMsg isEqualToString:@"Captcha needed"]){ isCaptcha = YES; // NSString *captcha_sid = [[dict objectForKey:@"error"] objectForKey:@"captcha_sid"]; NSString *captcha_img = [[dict objectForKey:@"error"] objectForKey:@"captcha_img"]; [[NSUserDefaults standardUserDefaults] setObject:captcha_img forKey:@"captcha_img"]; [[NSUserDefaults standardUserDefaults] setObject:captcha_sid forKey:@"captcha_sid"]; // url [[NSUserDefaults standardUserDefaults] setObject:reqURl forKey:@"request"]; [[NSUserDefaults standardUserDefaults] synchronize]; [self getCaptcha]; } return dict; } return nil; }
[self getCaptcha];
- (void) getCaptcha { NSString *captcha_img = [[NSUserDefaults standardUserDefaults] objectForKey:@"captcha_img"]; UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:@" :\n\n\n\n\n" message:@"\n" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil]; UIImageView *imageView = [[[UIImageView alloc] initWithFrame:CGRectMake(12.0, 45.0, 130.0, 50.0)] autorelease]; imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:captcha_img]]]; [myAlertView addSubview:imageView]; UITextField *myTextField = [[[UITextField alloc] initWithFrame:CGRectMake(12.0, 110.0, 260.0, 25.0)] autorelease]; [myTextField setBackgroundColor:[UIColor whiteColor]]; // myTextField.autocorrectionType = UITextAutocorrectionTypeNo; // myTextField.autocapitalizationType = UITextAutocapitalizationTypeNone; myTextField.tag = 33; [myAlertView addSubview:myTextField]; [myAlertView show]; [myAlertView release]; } - (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex { if(isCaptcha && buttonIndex == 1){ isCaptcha = NO; UITextField *myTextField = (UITextField *)[actionSheet viewWithTag:33]; [[NSUserDefaults standardUserDefaults] setObject:myTextField.text forKey:@"captcha_user"]; NSLog(@"Captcha entered: %@",myTextField.text); // NSString *request = [[NSUserDefaults standardUserDefaults] objectForKey:@"request"]; NSDictionary *newRequestDict =[self sendRequest:request withCaptcha:YES]; NSString *errorMsg = [[newRequestDict objectForKey:@"error"] objectForKey:@"error_msg"]; if(errorMsg) { [self sendFailedWithError:errorMsg]; } else { [self sendSuccessWithMessage:@" !"]; } } }
- (NSDictionary *) sendRequest:(NSString *)reqURl withCaptcha:(BOOL)captcha { // , captcha_sid captcha_key if(captcha == YES){ NSString *captcha_sid = [[NSUserDefaults standardUserDefaults] objectForKey:@"captcha_sid"]; NSString *captcha_user = [[NSUserDefaults standardUserDefaults] objectForKey:@"captcha_user"]; // . , . reqURl = [reqURl stringByAppendingFormat:@"&captcha_sid=%@&captcha_key=%@", captcha_sid, [self URLEncodedString: captcha_user]]; } ...
- (IBAction)sendImageAction:(id)sender { if(!isAuth) return; UIImage *image = [UIImage imageNamed:@"test.jpg"]; NSString *user_id = [[NSUserDefaults standardUserDefaults] objectForKey:@"VKAccessUserId"]; NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"VKAccessToken"]; // 1 NSString *getWallUploadServer = [NSString stringWithFormat:@"https://api.vk.com/method/photos.getWallUploadServer?owner_id=%@&access_token=%@", user_id, accessToken]; NSDictionary *uploadServer = [self sendRequest:getWallUploadServer withCaptcha:NO]; // NSString *upload_url = [[uploadServer objectForKey:@"response"] objectForKey:@"upload_url"]; ...
[self sendPOSTRequest:upload_url withImageData:imageData];
... // 2 // NSData NSData *imageData = UIImageJPEGRepresentation(image, 1.0f); NSDictionary *postDictionary = [self sendPOSTRequest:upload_url withImageData:imageData]; // hash, photo, server NSString *hash = [postDictionary objectForKey:@"hash"]; NSString *photo = [postDictionary objectForKey:@"photo"]; NSString *server = [postDictionary objectForKey:@"server"]; ...
... // 3 // , id NSString *saveWallPhoto = [NSString stringWithFormat:@"https://api.vk.com/method/photos.saveWallPhoto?owner_id=%@&access_token=%@&server=%@&photo=%@&hash=%@", user_id, accessToken,server,photo,hash]; NSDictionary *saveWallPhotoDict = [self sendRequest:saveWallPhoto withCaptcha:NO]; NSDictionary *photoDict = [[saveWallPhotoDict objectForKey:@"response"] lastObject]; NSString *photoId = [photoDict objectForKey:@"id"]; ...
... // 4 // NSString *postToWallLink = [NSString stringWithFormat:@"https://api.vk.com/method/wall.post?owner_id=%@&access_token=%@&message=%@&attachment=%@", user_id, accessToken, [self URLEncodedString:@" "], photoId]; NSDictionary *postToWallDict = [self sendRequest:postToWallLink withCaptcha:NO]; NSString *errorMsg = [[postToWallDict objectForKey:@"error"] objectForKey:@"error_msg"]; if(errorMsg) { [self sendFailedWithError:errorMsg]; } else { [self sendSuccessWithMessage:@" !"]; } // ! !
NSString *logout = @"http://api.vk.com/oauth/logout";
- (IBAction)logout:(id)sender { // logout NSString *logout = @"http://api.vk.com/oauth/logout"; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:logout] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0]; NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; if(responseData){ NSDictionary *dict = [[JSONDecoder decoder] parseJSONData:responseData]; NSLog(@"Logout: %@", dict); // , isAuth = NO; [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"VKAccessUserId"]; [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"VKAccessToken"]; [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"VKAccessTokenDate"]; [[NSUserDefaults standardUserDefaults] synchronize]; [self sendSuccessWithMessage:@" !"]; } }
Logout: { error = "invalid_client"; "error_description" = "client_id is incorrect"; }
Source: https://habr.com/ru/post/133504/