Роман Дервишов Роман Дервишов - 3 months ago 50
Swift Question

apple watch http request

Using import, I can use this module for iPhone, but not for apple watch app.I also want to use this library for writing apple watch app. Is it possible? If possible, how?
Can you please provide an alternative if it is not possible?

Thanks beforehand

Simple example of http request for iPhone

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

}

Answer

Sample Http request in apple watch.

Include below key iPhone app's info.plist and watchkit extension's info.plist

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

In your pod file, add Alamofire to both target, i.e. iPhone and watchkit extension

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

Create your Network.swift file and add 'Target Membership' to both i.e. iPhone target and watchkit extension target.

Sample Network.swift will be,

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

Now somewhere in your code you can call this method as,

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

Hope this helps !!!

Comments