swift로 http 통신 또는 자습 노트 진행
서식
NSURL 생성 및 Safari 시작
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 사이트가 아닌 데이터를 가져올 수 없습니다.
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>api.tiqav.com</key>
<dict>
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
</dict>
GET HTTP Request(비동기식)
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.swiftimport 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 설치
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'
에 관해서는 당시 버전에 맞추어야 한다.bundle exec pod install
open test1.xcworkspace
이런 느낌의 화면이 나올 거예요.구축할 때 오류가 없음을 확인하십시오.[iOS] Swift를 통해 Rails와 협업하는 방법(보충 중)
실천해 보자[iOS] 스위프트를 통해 Rails와 협업하는 방법-Qita.
storyboard에서 객체 설정
Use Size Classes
를 취소하고 아이폰 사이즈로 변경했다.소스와 끈
다음
Reference
이 문제에 관하여(swift로 http 통신 또는 자습 노트 진행), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/tukiyo3/items/b55667d3cd31610837f1텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)