swift调用oc项目

第一步:创建和配置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相对路径。

swift调用oc项目

第二步:第三方项目依赖

对于第三方项目的依赖,一开始我打算用CocoaPods,但是过程曲折,最后一直报

[objc] view plaincopyswift调用oc项目swift调用oc项目
 
  1. <span style="font-size:14px;">ld: 218 duplicate symbols for architecture i386  
  2. clang: error: linker command failed with exit code 1 (use -v to see invocation)</span>  

我也没有办法了就把第三方项目源码拷贝到自己的项目里面,上图也可以看到我拷贝的事AFNetworking项目,然后在把源码加入到Build Phases--Compile Sources里面
swift调用oc项目

第三步:修改Bridging-Header.h

在Bridging-Header.h中写入#import "AFNetworking.h"

第四步:调用OC

前面的工作做完后我们就可以调用第三方项目的功能了

 1 //
 2 //  ViewController.swift
 3 //  DemoApp
 4 //
 5 //  Created by jiezhang on 14/10/24.
 6 //  Copyright (c) 2014年 jiezhang. All rights reserved.
 7 //
 8 
 9 import UIKit
10 
11 class ViewController: UIViewController {
12 
13     @IBOutlet weak var weatherInfo: UITextView!
14     override func viewDidLoad() {
15         super.viewDidLoad()
16         updateWeatherInfo()
17     }
18 
19     override func didReceiveMemoryWarning() {
20         super.didReceiveMemoryWarning()
21         // Dispose of any resources that can be recreated.
22     }
23 
24     
25     func updateWeatherInfo() {
26         let manager = AFHTTPRequestOperationManager()
27         let url = "http://api.openweathermap.org/data/2.5/weather"
28         println(url)
29         let params:NSDictionary = ["lat":"37.785834", "lon":"-122.406417", "cnt":0]
30         println(params)
31         manager.GET(url,
32             parameters: params,
33             success: { (operation: AFHTTPRequestOperation!,
34                 responseObject: AnyObject!) in
35                 self.weatherInfo.text = "JSON: " + responseObject.description!
36             },
37             failure: { (operation: AFHTTPRequestOperation!,
38                 error: NSError!) in
39                 self.weatherInfo.text = "Error: " + error.localizedDescription
40                
41         })
42     }
43 
44 <p>}</p>

第五步:运行界面

swift调用oc项目
下载地址:http://pan.baidu.com/s/1c0myIbA