Swift 및 AFNetworking의 간단한 샘플

rbenv 에서 ruby 과를 관리하게 되어, 다시 cocoapods 의 인스톨로부터 시작한 기억.

※2015/01 갱신



이 기사에서 작동하지 않는 분은 여기

준비



개발 환경



PC: MacOS X 10.9.4
Xcode: Version 6.1
Ruby: 2.1.3
Rails: 4.1.6

Cocoapods 설치


$ rbenv exec gem install cocoapods

프로젝트 디렉토리로 이동


$ cd /path/to/your/xcode/project

Podfile 만들기


$ vi Podfile

platform :ios, "7.0"
pod 'AFNetworking', '~> 2.0'
pod "AFNetworkActivityLogger", "~> 2.0"

Cocoapods 설치


$ pod setup
Setting up CocoaPods master repo
Updating ce725a5..4bf3048

Fast-forward

  ・・・中略・・・

From https://github.com/CocoaPods/Specs

   ce725a5..4bf3048  master     -> origin/master
Setup completed

외부 라이브러리 (AFNetworking 등) 설치


$ pod install
Analyzing dependencies
Downloading dependencies
Installing AFNetworkActivityLogger (2.0.3)
Using AFNetworking (2.4.1)
Generating Pods project
Integrating client project

[!] The use of implicit sources has been deprecated. To continue using all of the sources currently on your machine, add the following to the top of your Podfile:

    source 'https://github.com/CocoaPods/Specs.git'

프로젝트 열기


Xcode 를 시작하고 .xcodeproj 대신 .xcworkspace 의 프로젝트 파일을 엽니다.



코딩



로깅 설정



AppDelegate.swift
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        //ロギング開始
        AFNetworkActivityLogger.sharedLogger().level = .AFLoggerLevelDebug
        AFNetworkActivityLogger.sharedLogger().startLogging()

        return true
    }
}

통신 처리



FirstViewController.swift
class FirstViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        NSLog("AFNetwork Starts First Page!!!")

        //リクエスト
        let manager:AFHTTPRequestOperationManager = AFHTTPRequestOperationManager()
        let serializer:AFJSONRequestSerializer = AFJSONRequestSerializer()
        manager.requestSerializer = serializer
        manager.GET("http://localhost:3000/members.json", parameters: nil,
            success: {(operation: AFHTTPRequestOperation!, responsobject: AnyObject!) in
                        println("Success!!")
                        println(responsobject)
                     },
            failure: {(operation: AFHTTPRequestOperation!, error: NSError!) in
                        println("Error!!")
                     }
        )

    }
}

통신 로그


2014-10-13 23:53:19.436 CocoapadSample[30736:177940] AFNetwork Starts First Page!!!
2014-10-13 23:53:19.563 CocoapadSample[30736:177940] GET 'http://localhost:3000/members.json': {
    "Accept-Language" = "en;q=1";
    "User-Agent" = "CocoapadSample/1 (iPhone Simulator; iOS 8.1; Scale/2.00)";
} (null)
2014-10-13 23:53:19.564 CocoapadSample[30736:177940] 200 'http://localhost:3000/members.json' [0.0011 s]: {
    "Cache-Control" = "max-age=0, private, must-revalidate";
    Connection = "Keep-Alive";
    "Content-Length" = 80;
    "Content-Type" = "application/json; charset=utf-8";
    Date = "Mon, 13 Oct 2014 14:53:19 GMT";
    Etag = "\"e25874e5c93e096f40461ae7ea30c135\"";
    Server = "WEBrick/1.3.1 (Ruby/2.1.3/2014-09-19)";
    "X-Content-Type-Options" = nosniff;
    "X-Frame-Options" = SAMEORIGIN;
    "X-Request-Id" = "13c2e6cf-9b4d-40b7-8ff6-e688527ce991";
    "X-Runtime" = "0.023255";
    "X-Xss-Protection" = "1; mode=block";
} [{"id":1,"name":"ほげほげ","age":99,"url":"http://localhost:3000/members/1.json"}]
Success!!
(
        {
        age = 99;
        id = 1;
        name = "\U7530\U5cf6\U7530\U5cf6";
        url = "http://localhost:3000/members/1.json";
    }
)

통신할 수 있었다.

Lovely Swift!!!

좋은 웹페이지 즐겨찾기