第一步:创建和配置Bridging-Header.h
Swift与OC进行混编,首先要有一个.h文件,这里使用Bridging-Header.h然后设置项目的Build Settings--Swift Compiler--Objective-C Bridging Header内容为DemoApp/Bridging-Header.h,这个与Bridging-Header.h位置有关,从项目的根目录开始在Objective-C Bridging Header选项里面写入Bridging-Header.h相对路径。
第二步:第三方项目依赖
对于第三方项目的依赖,一开始我打算用CocoaPods,但是过程曲折,最后一直报
- <span style="font-size:14px;">ld: 218 duplicate symbols for architecture i386
- clang: error: linker command failed with exit code 1 (use -v to see invocation)</span>
第三步:修改Bridging-Header.h
在Bridging-Header.h中写入#import "AFNetworking.h"
第四步:调用OC
前面的工作做完后我们就可以调用第三方项目的功能了
- //
- // ViewController.swift
- // DemoApp
- //
- // Created by jiezhang on 14/10/24.
- // Copyright (c) 2014年 jiezhang. All rights reserved.
- //
- import UIKit
- class ViewController: UIViewController {
- @IBOutlet weak var weatherInfo: UITextView!
- override func viewDidLoad() {
- super.viewDidLoad()
- updateWeatherInfo()
- }
- override func didReceiveMemoryWarning() {
- super.didReceiveMemoryWarning()
- // Dispose of any resources that can be recreated.
- }
- func updateWeatherInfo() {
- let manager = AFHTTPRequestOperationManager()
- let url = "http://api.openweathermap.org/data/2.5/weather"
- println(url)
- let params:NSDictionary = ["lat":"37.785834", "lon":"-122.406417", "cnt":0]
- println(params)
- manager.GET(url,
- parameters: params,
- success: { (operation: AFHTTPRequestOperation!,
- responseObject: AnyObject!) in
- self.weatherInfo.text = "JSON: " + responseObject.description!
- },
- failure: { (operation: AFHTTPRequestOperation!,
- error: NSError!) in
- self.weatherInfo.text = "Error: " + error.localizedDescription
- })
- }
- <p>}</p>
第五步:运行界面
下载地址:http://pan.baidu.com/s/1c0myIbA