LoginSignup
15
17

More than 5 years have passed since last update.

swiftでhttp通信とか自習メモ

Last updated at Posted at 2015-10-03
  • Xcode7.0.1, iOS9.0.2で確認

書式

NSURLを生成してSafari起動

スクリーンショット 2015-10-03 14.11.12.png

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サイトのデータが取得できない

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.

スクリーンショット 2015-10-03 14.30.39.png

  • 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 (非同期)

スクリーンショット 2015-10-03 15.26.01.png

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()
    }
}

cocoapodsでAlamofireをインストール

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

こんな感じの画面が表示される。ビルドしてエラーが出ないことを確認。

スクリーンショット 2015-10-03 15.53.17.png

【iOS】SwiftでRailsと連携する方法 (追記中)

スクリーンショット 2015-10-03 15.56.31.png
スクリーンショット 2015-10-03 15.57.06.png

storyboardにオブジェクトを設置

  • Storyboardのデバイス画面サイズが大きいので、Use Size Classesのチェックを外しiPhoneサイズに変更。

スクリーンショット 2015-10-03 16.24.52.png

  • View,Button,Label,TextViewをMain.storyboardのViewに設置

スクリーンショット 2015-10-03 16.31.19.png

ソースとひも付け

  • Text ViewをtextViewという名前でOutlet接続
  • ButtonをtapSaveBtnという名前でAction接続

76f0d9ce-aa0b-70c4-c110-cb543bdeee4a.png

続きは今度

15
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
17