苹果手表http请求

时间:2016-08-31 10:20:00

标签: swift watchkit apple-watch watch-os-2

使用导入,我可以将此模块用于iPhone,但不能用于Apple Watch应用程序。我也想使用此库来编写Apple Watch应用程序。可能吗?如果可能,怎么样?    如果不可能,请你提供替代方案吗?

事先谢谢

iPhone的http请求的简单示例

import Alamofire
Alamofire.request(.GET, requestUrl, headers: self.headers(), encoding:.JSON).responseJSON 
{
  (rJ) -> Void in

  let data = rJ.result.value

  let err = rJ.result.error

}

1 个答案:

答案 0 :(得分:4)

Apple Watch中的示例Http请求。

包括以下关键iPhone应用程序的info.plist和watchkit扩展名的info.plist

    <key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

在您的pod文件中,将Alamofire添加到两个目标,即iPhone和watchkit扩展

source 'https://github.com/CocoaPods/Specs.git'
use_frameworks!

target 'MyApp' do
    platform :ios, '9.0'
      pod 'Alamofire', '~> 3.4'
end

target 'MyApp WatchKit Extension' do
    platform :watchos, '2.0'
    pod 'Alamofire', '~> 3.4'
end

创建您的Network.swift文件并将“目标成员资格”添加到iPhone目标和watchkit扩展目标。

示例Network.swift将是,

import Foundation
import Alamofire

struct NetworkService
{
  func executeRequest(method: Alamofire.Method,parameters:String:AnyObject]?, URLString:URLStringConvertible, completionHandler: Response<AnyObject, NSError> -> Void)
  {
    Alamofire.request(method, URLString, parameters: parameters,encoding: .JSON, headers: nil) .responseJSON { response in
        completionHandler(response)
    }
  }
}

现在,您可以在代码中的某处将此方法称为

var sampleNWRequest:NetworkService = NetworkService()
sampleNWRequest.executeRequest(.GET, parameters: nil, URLString:"your url", completionHandler: { response in
  print(response.result.value)
 )

希望这有帮助!!!