swift로 http 통신 또는 자습 노트 진행

12913 단어 SwiftAlamofire
  • Xcode7.0.1, iOS9.0.2 확인
  • 서식

  • The Swift Programming Language (Swift 2): The Basics
  • NSURL 생성 및 Safari 시작

  • [Swift] NSURL을 생성하고 Safari Advent Calendar를 시작합니다.
  • Swift로 URL 인코딩 - Qiita

  • DataViewController.swift
    import UIKit
    class DataViewController: UIViewController {
        override func viewDidLoad() {
            super.viewDidLoad()
            self.openSafari()
        }
        func openSafari() {
            let url : NSString = "http://api.tiqav.com/search/random.json"
            let urlStr : NSString = url.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
            let searchURL : NSURL = NSURL(string: urlStr as String)!
            // ブラウザ起動
            if UIApplication.sharedApplication().canOpenURL(searchURL){
                UIApplication.sharedApplication().openURL(searchURL)
            }
        }
    }
    

    SSL/TLS 사이트가 아닌 데이터를 가져올 수 없습니다.

  • XCode7(iOS 9)로 가장 먼저 발생한 오류와 대책 방법 및 -Qiita
  • App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.
  • api.tiqav.com의 http를 허용하기 위해 다음과 같이 기술합니다
  • Info.plist
    <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSExceptionDomains</key>
        <dict>
            <key>api.tiqav.com</key>
            <dict>
                <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
                <true/>
            </dict>
        </dict>
    </dict>
    

    GET HTTP Request(비동기식)

  • iOS-NSURLSession을 통해 HTTP request의 샘플 코드 Swift 버전 - Qiita 던지기

  • DataViewController.swift
    class DataViewController: UIViewController {
        override func viewDidLoad() {
            super.viewDidLoad()
            self.testGet()
        }
        func testGet() {
            let request: Request = Request()
            let url: NSURL = NSURL(string: "http://api.tiqav.com/search/random.json")!
            request.get(url)
        }
    }
    
    Request.swift
    import Foundation
    
    class Request {
        let session: NSURLSession = NSURLSession.sharedSession()
    
        // GET METHOD
        func get(url : NSURL) {
            let config = NSURLSessionConfiguration.defaultSessionConfiguration()
            let session = NSURLSession(configuration: config)
            let req = NSURLRequest(URL: url)
    
            let task = session.dataTaskWithRequest(req, completionHandler: {
                (data, resp, err) in
                print(resp!.URL!)
                print(NSString(data: data!, encoding: NSUTF8StringEncoding))
            })
            task.resume()
        }
    }
    

    cocoappods로 Alam ofire 설치

  • Swift-[iOS] cocoapods 설치 방법 - Qita
  • Alamofire에 대한 14건의 투고 - Qita
  • Alamofire/Alamofire · GitHub
  • iOS 프로젝트로 이동
    sudo gem install bundler
    cd ~/Documents/test1
    
    bundle init
    
    Gemfile
      source "https://rubygems.org"
    + gem "cocoapods"
    
    bundle install --path=vendor/bundle
    bundle exec pod setup
    bundle exec pod init
    
    Podfile
     # Uncomment this line to define a global platform for your project
     # platform :ios, '6.0'
    +use_frameworks!
    
     target 'test1' do
    +    pod 'Alamofire', '~> 2.0.2'
     end
    
     target 'test1Tests' do
    
     end
    
     target 'test1UITests' do
    
     end
    
  • pod 'Alamofire', '~> 2.0.2'에 관해서는 당시 버전에 맞추어야 한다.
  • Xcode 종료 후 구현
    bundle exec pod install
    open test1.xcworkspace
    
    이런 느낌의 화면이 나올 거예요.구축할 때 오류가 없음을 확인하십시오.

    [iOS] Swift를 통해 Rails와 협업하는 방법(보충 중)


  • 실천해 보자[iOS] 스위프트를 통해 Rails와 협업하는 방법-Qita.


  • storyboard에서 객체 설정

  • 스토리보드는 디바이스 화면 크기가 커서 검사Use Size Classes를 취소하고 아이폰 사이즈로 변경했다.
  • 는 View, Button, Label, TextView Main을storyboard의 View에 설치

  • 소스와 끈

  • Text View는 textView 이름으로 Outlet
  • 을 연결합니다.
  • Buton을 tapSaveBtn의 이름으로 Action 연결

  • 다음

    좋은 웹페이지 즐겨찾기