질문에 관한 내용은 카카오스토리 API이고, 플랫폼은 iOS SDK 8.1, 언어는 Swift입니다.
Swift가 나오고, 애플이 Swift와 Objective-C를 둘 다 사용할 수 있도록 해준 덕분에 현재 MyApp-Bridging-Header.h 파일에
//
// Use this file to import your target's public headers that you would like to expose to Swift.
//
#import <KakaoOpenSDK/KakaoOpenSDK.h>
이렇게 올려놓고 쓰고 ViewController.swift 파일에서 호출해서 쓰고있습니다.
그럼.. 염치 불구하고 질문 올리겠습니다..
아래에 있는 자료가 원래 KakaoDevelopers_ (https://developers.kakao.com/) 에 업로드 되어있는 Objective-C로 작성 된 기존 KakaoStorySampleLoginViewController.m 파일입니다.
/**
* Copyright 2014 Daum Kakao Corp.
*
* Redistribution and modification in source or binary forms are not permitted without specific prior written permission.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#import "KakaoStorySampleAppDelegate.h"
#import "KakaoStorySampleLoginViewController.h"
#import <KakaoOpenSDK/KakaoOpenSDK.h>
@implementation KakaoStorySampleLoginViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = @"Login";
}
return self;
}
- (void)loadView {
[super loadView];
// logo display
int marginBottom = 25;
UIImage *kakaoLogoImage = [KOImages kakaoLogo];
UIImageView *kakaoLogoImageView = [[UIImageView alloc] initWithImage:kakaoLogoImage];
kakaoLogoImageView.frame = CGRectMake((self.view.frame.size.width - kakaoLogoImage.size.width) / 2, (self.view.frame.size.height - kakaoLogoImage.size.width - marginBottom) / 2, kakaoLogoImage.size.width, kakaoLogoImage.size.height);
kakaoLogoImageView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
[self.view addSubview:kakaoLogoImageView];
// button display
UIButton *kakaoAccountConnectButton = [self createKakaoAccountConnectButton];
[self.view addSubview:kakaoAccountConnectButton];
}
- (UIButton *)createKakaoAccountConnectButton {
// button position
int xMargin = 30;
int marginBottom = 25;
CGFloat btnWidth = self.view.frame.size.width - xMargin * 2;
int btnHeight = 42;
UIButton *btnKakaoLogin
= [[KOLoginButton alloc] initWithFrame:CGRectMake(xMargin, self.view.frame.size.height - btnHeight - marginBottom, btnWidth, btnHeight)];
btnKakaoLogin.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth;
// action
[btnKakaoLogin addTarget:self action:@selector(invokeLoginWithTarget:) forControlEvents:UIControlEventTouchUpInside];
return btnKakaoLogin;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
} else {
return YES;
}
}
#pragma mark - actions
- (IBAction)invokeLoginWithTarget:(id)sender {
[[KOSession sharedSession] close];
[[KOSession sharedSession] openWithCompletionHandler:^(NSError *error) {
if ([[KOSession sharedSession] isOpen]) {
// login success.
NSLog(@"login success.");
[[[UIApplication sharedApplication] delegate] performSelector:@selector(showMainView)];
} else {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"에러"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:@"확인"
otherButtonTitles:nil];
[alertView show];
}
}];
}
- (IBAction)invokeCancelLoginWithTarget:(id)sender {
[[KOSession sharedSession] close];
}
- (IBAction)invokeToggleStatusBar:(id)sender {
[[UIApplication sharedApplication] setStatusBarHidden:![UIApplication sharedApplication].statusBarHidden withAnimation:YES];
}
@end
그리고 아래가 지금 제가 만들고 있는 Swift 파일입니다.
//
// ViewController.swift
// ManyPost
//
// Created by CenoX on 2014. 12. 15..
// Copyright (c) 2014년 CenoX. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*==========================================*/
/*========Starting Make View for Kakao API =======*/
/*==========================================*/
override func loadView() {
super.loadView()
var marginBottom: CGFloat
marginBottom = 25
var kakaoLogoImage: UIImage!
kakaoLogoImage = KOImages.kakaoLogo()
var kakaoLogoImageView: UIImageView!
kakaoLogoImageView.image = kakaoLogoImage
kakaoLogoImageView.frame = CGRectMake((self.view.frame.size.width - kakaoLogoImage.size.width) / 2, (self.view.frame.size.height - kakaoLogoImage.size.width - marginBottom) / 2, kakaoLogoImage.size.width, kakaoLogoImage.size.height)
kakaoLogoImageView.autoresizingMask = UIViewAutoresizing.FlexibleLeftMargin | UIViewAutoresizing.FlexibleRightMargin | UIViewAutoresizing.FlexibleTopMargin | UIViewAutoresizing.FlexibleBottomMargin
self.view.addSubview(kakaoLogoImageView)
var kakaoAccountConnectButton: UIButton!
kakaoAccountConnectButton.addTarget(self, action: "createKakaoAccountConnectButton", forControlEvents: .TouchUpInside)
/*
/*Break Point*/
Original Source (Objective-C)
/*==========================================*/
UIButton *kakaoAccountConnectButton = [self createKakaoAccountConnectButton];
/*==========================================*/
*/
}
func createKakaoAccountConnectButton()
//Action for kakaoAccountConnectButton
{
var xMargin:CGFloat = 30
var marginBottom: CGFloat = 25
var btnWidth: CGFloat = self.view.frame.size.width - xMargin * 2
var btnHeight: CGFloat = 42
var btnKakaoLogin: UIButton!
btnKakaoLogin.frame = CGRectMake(xMargin, self.view.frame.size.height - btnHeight - marginBottom, btnWidth, btnHeight)
btnKakaoLogin.autoresizingMask = UIViewAutoresizing.FlexibleTopMargin | UIViewAutoresizing.FlexibleBottomMargin
btnKakaoLogin.addTarget(self, action: "invokeLoginWithTarget", forControlEvents: .TouchUpInside)
}
/*==========================================*/
/*============#pragma mark - actions===========*/
/*==========================================*/
@IBAction func invokeLoginWithTarget() {
var errors: NSError
KOSession.sharedSession().close()
KOSession.sharedSession().openWithCompletionHandler(errors) {
if (KOSession.sharedSession().isOpen()) {
println("Login Success")
UIApplication.sharedApplication().delegate?.respondsToSelector("ShowMainView")
} else {
var alert = UIAlertController(title: "Error", message: errors.localizedDescription, preferredStyle: .Alert)
}
}
}
}
이렇게 적었습니다만 강조하고 싶은 부분은 두부분 입니다.
일단 첫번째
var errors: NSError
KOSession.sharedSession().openWithCompletionHandler(errors) {
기존 소스코드는
[[KOSession sharedSession] openWithCompletionHandler:^(NSError *error) {
라고 처리가 되어 있습니다만, Swift상에서 *Handler:^(NSError *error) 부분을 어떻게 처리해야 할 지 모르겠습니다..
직접 선언 된 헤더파일을 살펴보면
/*!
기기의 로그인 수행 가능한 카카오 앱에 로그인 요청을 전달한다.
@param completionHandler 요청 완료시 실행될 block. 오류 처리와 로그인 완료 작업을 수행한다.
*/
- (void)openWithCompletionHandler:(KOSessionCompletionHandler)completionHandler;
라고 적혀 있고, 스위프트에서 구문을 호출 할 때 *CompletionHandler를 어떻게 처리해야할 지에 대한 설명도 간략히 나와있습니다만
아무리 고심해도 이 부분을 어떻게 처리해야 할지 모르겠습니다..
도와주세요..ㅠ
두번째는
UIApplication.sharedApplication().delegate?.respondsToSelector("ShowMainView")
입니다.
기존 소스코드를 보면
[[[UIApplication sharedApplication] delegate] performSelector:@selector(showMainView)];
이렇게 처리가 되어 있습니다만
NSObject안에 속해있는 -performSelector: 구문은 swift에서는 사용할 수 없습니다..ㅠ ( http://stackoverflow.com/questions/24158427/alternative-to-performselector-in-swift )
사용 가능하지 않다는 말에, 자포자기 하며 사용할 만한 소스코드를 찾아서 적은 코드가 바로 저
UIApplication.sharedApplication().delegate?.respondsToSelector("ShowMainView")
입니다만, 작동 할 것 같진 않아보입니다.
'Dev. > iOS Dev.' 카테고리의 다른 글
iOS에 내장된 Framework를 이용하여, 트위터에 글 포스팅하는 소스코드. (0) | 2015.02.13 |
---|---|
kakaoDev Talk. -절망 (0) | 2014.12.16 |
KakaoDev Talk -삽질 (0) | 2014.12.16 |
iOS 학교정보 파싱 소스코드 (0) | 2014.09.08 |