Showing posts with label alamofire. Show all posts
Showing posts with label alamofire. Show all posts

Tuesday, July 17, 2018

Request time out error 1001 using alamofire in ios swift?

Leave a Comment

Here i am sending parameter value like username, user toke, post id, etc to backend using alamofire. if status success then, notification will will send from backend. Inside postnotification function i have tried post method code using alamofire and datatask method but it does not work. In console i am getting request time out or nothing.

Here is my code :

   func postNotification(postItem: String, post: Post) {    //                declare parameter as a dictionary which contains string as key and value combination. considering inputs are valid        print("Get token from post:::",post.token)     print(postItem)     let token = UserDefaults.standard.string(forKey: "token")             //create the url with URL       var parameters       = [String:Any]()      parameters["count"]  = post.likeCount!     parameters["likedby"]  = currentName     parameters["postId"] = postItem     parameters["token"] = post.token!      let Url = String(format: "http://highavenue.co:9000/likesnotification")     guard let serviceUrl = URL(string: Url) else { return }     //        let loginParams = String(format: LOGIN_PARAMETERS1, "test", "Hi World")     let parameterDictionary = ["username" : "Test", "password" : "123456"]     var request = URLRequest(url: serviceUrl)     request.httpMethod = "POST"     request.setValue("Application/json", forHTTPHeaderField: "Content-Type")     guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else {         return     }     request.httpBody = httpBody      let session = URLSession.shared     session.dataTask(with: request) { (data, response, error) in         if let response = response {             print(response)         }         if let data = data {             do {                 let json = try JSONSerialization.jsonObject(with: data, options: [])                 print(json)             }catch {                 print(error)             }         }         }.resume()     //        let headers: HTTPHeaders = ["Content-Type" :"application/x-www-form-urlencoded"]   //   //        Alamofire.request("http://highavenue.co:9000/likesnotification", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in  //                    //             original URL request  //                        print("Request is :",response.request!)  //  //                        // HTTP URL response --> header and status code  //                        print("Response received is :",response.response)  //  //                        // server data : example 267 bytes    //                        print("Response data is :",response.data)   //     //                        // result of response serialization : SUCCESS / FAILURE    //                        print("Response result is :",response.result)    //    //                        debugPrint("Debug Print :", response)   //    //    //        }     //        Alamofire.request("http://highavenue.co:9000/likesnotification", method: HTTPMethod.post, parameters: json, encoding: JSONEncoding.default, headers: headers).responseJSON { response in    //     //            // original URL request    //            print("Request is :",response.request!)    //   //            // HTTP URL response --> header and status code     //            print("Response received is :",response.response)    //   //            // server data : example 267 bytes    //            print("Response data is :",response.data)    //    //            // result of response serialization : SUCCESS / FAILURE   //            print("Response result is :",response.result)   //   //            debugPrint("Debug Print :", response)   //        }      } 

Any help much appreciated pls..

1 Answers

Answers 1

Yaah solved it. There was a negligence mistake. I used an additional slash in the URL. I changed the web API to a different folder and I made this mistake while changing it in the iOS code. and Also Set your timeout interval here.

let RequestData = NSMutableURLRequest(URL: NSURL.init(string: "Your URL Hear")!) RequestData.HTTPMethod = "POST" RequestData.timeoutInterval = 250 // Time interval here.  Alamofire.request(RequestData).responseJSON { (responseData) -> Void in     if((responseData.result.value) != nil) { // response         print(responseData.result.value!)     } }     

Hope this Help You..

Read More

Saturday, June 3, 2017

Alamofire: cache large files downloaded to the Documents folder

Leave a Comment

I use this piece of code to download MP3 files to the documents directory:

let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory) Alamofire.download(theUrl!, to:destination).response { response in     // stuff }.downloadProgress { progress in     // Stuff } 

The file downloads fine, but if i close the app and start it again, the download restarts from 0. What i want is for the file to be cached and fetched immediatly. My understanding of Alamofire is that the file is downloaded to a temporary folder and then moved to the Documents folder, is this what causes the cache to not happend ?

Thanks a lot

1 Answers

Answers 1

Please check the following references in order:
1. https://github.com/Alamofire/Alamofire/issues/1104
2. https://github.com/Alamofire/Alamofire#resuming-a-download
3. https://stackoverflow.com/a/39347461/3549695

In summary:
You need to use the request.cancel() API to generate the resumeData before your app exit.
Then you use the resume API with the resumeData to resume the request when the app restart.
There is no guarantee that it will always work. If it fails then it will still restart from 0.

There was a mentioning of issue with iOS 10 in reference (2) above that prevent this from working properly. But the update on StackOverflow (ref. 3) has a report that it has been fixed in iOS 10.2

Read More

Monday, May 15, 2017

Alamofire request always fails with “The request timed out” if Socket.io is connected

Leave a Comment

if socket.io is connected Alamofire is not working as expected, always getting req time out error. Alamofire works if i disable Socket.io

this is the error i'm getting

Error Domain=NSURLErrorDomain Code=-1001 "The request timed out."  UserInfo={NSUnderlyingError=0x60800044c720  {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)"  UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=https://enpoint.json, NSErrorFailingURLKey=https://enpoint.json,  _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102, NSLocalizedDescription=The request timed out.} 

and this

_tcp_connection_write_eof_block_invoke Write close callback received error: [89] Operation canceled 

kind of similar issue reported on git https://github.com/Alamofire/Alamofire/issues/1545 but no answers.

I don't know what i'm doing wrong! Any help would be appreciated

1 Answers

Answers 1

I was able to fix this issue by changing alamofire parameter encoding. By default Alamofire sets encoding to URLEncoding if you are not passing any encoding argument. Use URLEncoding for GET and DELETE request. Use JSONEncoding.default for all other requests (API should have support for this).

Still i'm not sure why it was working w/o socket and wasn't working with socket on.

Read More

Sunday, April 30, 2017

Resume download after killing or putting on background the application

Leave a Comment

I have some issues when I want to resume a download operation. I am using Alamofire 4.4 and I made my tests on iOS 9 and 10. Here is my use cases:

1- A download operation is in progress, I cancel the request (resumeData is generated and saved) and then I put the application on background. After relaunching the application, I resume the download (using the resumeData) some times the download is being resumed and sometimes is being restarted. Is it a normal behaviour ? And are there any solution if not ?

2- A download operation is in progress, and i kill the application. Downloaded data seems to be lost and I can't resume the download. Is there any solution to get the resumeData and resume the download after restarting the application ?

Thank you.

1 Answers

Answers 1

This may not be a direct answer for your question but you should definitely check those: http://benscheirman.com/2016/09/designing-a-robust-large-file-download-system/ and http://benscheirman.com/2016/10/background-downloads/

Read More

Wednesday, March 15, 2017

How to use a Proxy Server with Alamofire 4 and Swift 3

Leave a Comment

Please don't mark as duplicate, I haven't been able to solve my Issue with the existing threads.

I'm trying to use my Proxy for an API request that needs a specified IP. To debug my issue, I'm requesting the IP from a webservice.

This is my current code:

import UIKit import Alamofire  class ViewController: UIViewController {      var requestManager = Alamofire.SessionManager.default      override func viewDidLoad() {         super.viewDidLoad()     }      override func viewDidAppear(_ animated: Bool) {         super.viewDidAppear(true)          var proxyConfiguration = [NSObject: AnyObject]()         proxyConfiguration[kCFNetworkProxiesHTTPProxy] = "http://xxx@eu-west-static-01.quotaguard.com" as AnyObject?         proxyConfiguration[kCFNetworkProxiesHTTPPort] = "9293" as AnyObject?         proxyConfiguration[kCFNetworkProxiesHTTPEnable] = 1 as AnyObject?          let cfg = Alamofire.SessionManager.default.session.configuration         cfg.connectionProxyDictionary = proxyConfiguration          let ip = URL(string: "https://api.ipify.org?format=json")          requestManager = Alamofire.SessionManager(configuration: cfg)         requestManager.request(ip!).response { response in             print("Request: \(response.request)")             print("Response: \(response.response)")             print("Error: \(response.error)")              if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {                 print("Data: \(utf8Text)")             }         }     } } 

The problem: the responsed IP is the same with or without the proxyConfiguration. Any help is very appreciated.

PS: physical device used.

1 Answers

Answers 1

I think the working (supposed to be deprecated) keys are:

kCFStreamPropertyHTTPSProxyHost kCFStreamPropertyHTTPSProxyPort 

Could you try this code?

import UIKit import Alamofire  class ViewController: UIViewController {      var requestManager = Alamofire.SessionManager.default      override func viewDidLoad() {         super.viewDidLoad()     }      override func viewDidAppear(_ animated: Bool) {         super.viewDidAppear(true)           var proxyConfiguration = [NSObject: AnyObject]()          proxyConfiguration[kCFNetworkProxiesHTTPProxy] = "eu-west-static-01.quotaguard.com" as AnyObject?          proxyConfiguration[kCFNetworkProxiesHTTPPort] = "9293" as AnyObject?          proxyConfiguration[kCFNetworkProxiesHTTPEnable] = 1 as AnyObject?          proxyConfiguration[kCFStreamPropertyHTTPSProxyHost as String] = "eu-west-static-01.quotaguard.com"          proxyConfiguration[kCFStreamPropertyHTTPSProxyPort as String] = 9293          proxyConfiguration[kCFProxyUsernameKey as String] = xxx          //proxyConfiguration[kCFProxyPasswordKey as String] = "pwd if any"         let cfg = Alamofire.SessionManager.default.session.configuration         cfg.connectionProxyDictionary = proxyConfiguration          let ip = URL(string: "https://api.ipify.org?format=json")          requestManager = Alamofire.SessionManager(configuration: cfg)         requestManager.request(ip!).response { response in             print("Request: \(response.request)")             print("Response: \(response.response)")             print("Error: \(response.error)")              if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {                 print("Data: \(utf8Text)")             }         }     } } 

Also please make sure your proxy server is configured to handle https requests.

Note: It might give deprecated warning for those keys but keys are still working (see https://forums.developer.apple.com/thread/19356#131446)

Note: I posted the same answer here. Posting the same here as it was applicable here as well. Alamofire is using same URLSessionConfiguration.

Read More

Tuesday, October 11, 2016

Alamofire 4 and special characters in JSON

Leave a Comment

I've got a problem with special characters with Alamofire 4.
The JSON contains æ, ø and å and the browser shows them fine, also my previous solution using SwiftyJSON did.

Alamofire 4 shows something like this instead:

U00e6 

Using this call:

Alamofire.request(specificURL, method: .get, parameters: param, encoding: URLEncoding.default, headers: nil).responseJSON { (response: DataResponse<Any>) in     print(response) } 

What to do to solve this?

4 Answers

Answers 1

Edit:

Alamofire.request(url, method: .get, parameters: param, encoding: JSONEncoding.default)         .responseJSON { response in              switch response.result {             case .success(let value) :                  print(response.request)  // original URL request                 print(response.response) // HTTP URL response                 print(response.data)     // server data                 print(response.result)   // result of response serialization                  if let JSON = response.result.value as! [String:AnyObject]!{                     print("JSON: ",JSON)                     self.arrUser = Mapper<Users>().mapArray(JSONArray:JSON["user"] as! [[String : Any]])!                     self.tableView.reloadData()                 }             case .failure(let encodingError):                 //Print error             }     } 

I got the issue that I have added æ in json response and try to print.

Output:

JSON:  Optional(<__NSArrayI 0x600000050320>( {     "email_address" = "testwts06@gmail.com";      username = "testwts06 \U00e6"; }, {     "email_address" = "testwts01@gmail.com";     username = "testwts01 \U00eb"; }, {     "email_address" = "testwts100@gmail.com";     username = testwts100; }) 

While displaying it display in correct format.

image

Answers 2

Swift 3 update for Ekta's answer:

let encodedURL = specificURL.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed) 

Answers 3

Seems the typical serialization error due to wrong JSON encoding, probably your response status code is 3840.

JSON text SHALL be encoded in UTF-8, UTF-16, or UTF-32.

You could try to convert the response data to correct UTF8 encoding:

let datastring = NSString(data: response.data!, encoding: String.Encoding.isoLatin1.rawValue) let data = datastring!.data(using: String.Encoding.utf8.rawValue) do {      let object = try JSONSerialization.jsonObject(with: data!, options: .allowFragments)      let jsonDic = object as! NSDictionary      print("  ok, successfully converted..\(jsonDic)") } catch let aError as Error {      // print and handle aError  } 

Hope it helps you.

Answers 4

Here is a simple String extension that solves the issue:

extension String {     func fixUnicode() -> String {         var copy = self as NSString         let regex = try! NSRegularExpression(pattern: "\\\\U([A-Z0-9]{4})", options: .caseInsensitive)         let matches = regex.matches(in: self, options: [], range: NSMakeRange(0, characters.count)).reversed()         matches.forEach {             let char = copy.substring(with: $0.rangeAt(1))             copy = copy.replacingCharacters(in: $0.range, with: String(UnicodeScalar(Int(char, radix: 16)!)!)) as NSString         }         return copy as String     } } 
Read More

Saturday, April 9, 2016

Always get build error : No such module 'Alamofire'

Leave a Comment

I followed the instruction of Alamofire in github,

I created an xcode project named cocoapods-test & I closed it.

I go to the project folder run pod init command which generates a Podfile. Then I added the following code to the Podfile:

source 'https://github.com/CocoaPods/Specs.git' platform :ios, '8.0' use_frameworks!  pod 'Alamofire', '~> 3.0' 

Then, I run command pod install and this is the result in terminal:

Updating local specs repositories  CocoaPods 1.0.0.beta.6 is available. To update use: `gem install cocoapods --pre` [!] This is a test version we'd love you to try.  For more information see http://blog.cocoapods.org and the CHANGELOG for this version http://git.io/BaH8pQ.  Analyzing dependencies Downloading dependencies Installing Alamofire (3.3.0) Generating Pods project Integrating client project  [!] Please close any current Xcode sessions and use `cocoapods-test.xcworkspace` for this project from now on. Sending stats Pod installation complete! There is 1 dependency from the Podfile and 1 total pod installed. 

Then, in my project folder there is a new file called cocoapods-test.xcworkspace . I double clicked it which opens my xcode again, and I can see the Alamofire module.

Then, I opened my project's ViewController class, and import Alamofire . But no matter how many times I clean & build, I always get error No such module 'Alamofire' . Here is the screenshot:

enter image description here

Why I get this problem though I followed the instruction step by step?

(I am using XCode 7.2.1, Swift 2.1.1 & Alamofire 3.3.0)

======= UPDATE ========

I tried @LK Yeung 's answer, uncomment import Alamofire, then clean & build again, I got a bunch of compiler errors from Alarmofire:

enter image description here

4 Answers

Answers 1

I was having this exact same problem. Please make sure that you are on Xcode 7.3 and using Swift 2.2.

You can check your Swift version using xcrun swift -version. Updating Xcode to 7.3 should also automatically update Swift.

Updating Xcode resolved this issue for me.

Answers 2

You need to add the lib to 'the Link Binary With Libraries' section also

Answers 3

You need to build the project successfully once before using the library

comment import Alamofire -> build -> uncomment import Alamofire

Answers 4

You can try put pod 'Alamofire', '~> 3.0' like below. And run pod install again.

target 'yourtarget' do      pod 'Alamofire', '~> 3.0' end 
Read More

Monday, April 4, 2016

Multiple calls to a Alamofire request, get reference for each call

Leave a Comment

I have used Alamofire for uploading images in multipart form data. I am successful in achieving my target. Each time I upload an image, I call the "uploadDocWebService" function. So the number of times the function is called, is equal to the number of images. I am hopeless in identifying the result of each call. My images are uploaded successfully. In case there is a server failure, or internet connection failure the uploading fails, I cannot identify which image I should delete from the view, that has failed. I pass indexPath as a parameter for each image upload. But that indexPath updates to the latest image upload before I receive the result for the first image upload. Can any one suggest me a better approach for this situation.

Here is the code I use for image upload:

func uploadDocWebservice(fileUrl: NSURL , progressView : PWProgressView , index : String , imageData : NSData? , name : String , mimeType : String , uploadType : String){      let url = "\(kBaseURL)\(uploadDocsUrl)"      var type = String()     var networkGroupId = String(SingletonClass.sharedInstance.selectedNetworkId!)      if SingletonClass.sharedInstance.groupPopUp == true {          type = "group"         networkGroupId = String(SingletonClass.sharedInstance.selectedSubNetworkOrGroup!)      }else {          type = "network"     }      Alamofire.upload(         .POST,         url,         multipartFormData: { multipartFormData in              if uploadType == "Image" {                 multipartFormData.appendBodyPart( data: imageData! , name: "file", fileName: name, mimeType: mimeType)             }else {                 multipartFormData.appendBodyPart(fileURL: fileUrl, name: "file")             }             multipartFormData.appendBodyPart(data:"\(SingletonClass.sharedInstance.tokenId)".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"token")             multipartFormData.appendBodyPart(data:"\(type)".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"networkGroup")             multipartFormData.appendBodyPart(data:"\(networkGroupId)".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"networkGroupId")          },         encodingCompletion: { encodingResult in             switch encodingResult {             case .Success(let upload, _, _):                  upload.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in                      let ratio: Float = Float(totalBytesRead) / Float(totalBytesExpectedToRead)                     // Call main thread.                     dispatch_async(dispatch_get_main_queue(), {                         progressView.progress = ratio                     })                  }                  upload.responseJSON { response in                      let dataString = NSString(data: response.data!, encoding:NSUTF8StringEncoding)                     print(dataString)                      self.edited = true                      do{                          let json = try NSJSONSerialization.JSONObjectWithData(response.data!, options: .MutableLeaves) as? NSDictionary                          if let success = json!["success"] as? Int {                              if success == 1 {                                  let id = json!["response"]!.objectForKey("id") as! String                                 let docName = "\(json!["response"]!.objectForKey("name") as! String).\(json!["response"]!.objectForKey("ext") as! String)"                                 let dic = ["name" : docName , "Id" : id]                                 self.uploadedDocsIdArray.addObject(dic)                                 self.uploadedArrayJustNames.addObject(docName)                                 print(self.uploadedDocsIdArray)                              }else {                                  // delete image from view here                              }                          }                      }catch{                          // delete image from view here                         invokeAlertMethod("Error", msgBody: "Invalid Json", delegate: self)                      }                  }             case .Failure(let encodingError):                  print(encodingError)             }         }     )  } 

If I get to know the which result is associated to which call, that could help me delete that particular image from view.

1 Answers

Answers 1

You need to keep a reference to the original request, should be the same for upload requests I think. Try the following:

func uploadDocWebservice(fileUrl: NSURL , progressView : PWProgressView , index : String , imageData : NSData? , name : String , mimeType : String , uploadType : String) -> Request? {     return Alamofire.upload ... } 

Then you can simply have an array of requests i.e: var requests: [Request](). When calling Alamofire.upload / Alamofire .request - it returns a Request object.

You can then do:

var requests: [Request]() let request = uploadDocWebservice(...) requests.append(request) 

Then you can just loop through the array and check whatever request you wish.

Read More

Monday, March 7, 2016

Using Alamofire with an iOS 8.0 Embedded Framework

Leave a Comment

I am trying to use Alamofire within a custom framework that I am creating. I created my custom framework project, added the Podfile, installed Alamofire. I then created a sample project to test out my custom framework.

The sample project is compiling fine with my custom framework import, that is until I started making Alamofire calls within my framework. Now Xcode is complaining about "Missing require module 'Alamofire'" within my sample project. And if I add "import Alamofire" to the swift file, Xcode now complains about "No such module 'Alamofire'"

Is if possible to use a swift framework such as Alamofire within a custom framework, and does the project using my custom framework need to import the Alamofire framework as well?

2 Answers

Answers 1

Yes, it is possible to use Alamofire within your custom framework, but you need to also include Alamofire in the podfile of your sample project (the project that uses your framework). Your podfile should look like this:

platform :ios, '8.0' use_frameworks!  target 'MyApp' do #   pod 'MyFramework'  Include MyFramework if it is a cocoadpod    pod 'Alamofire' end 

The error "Missing required module 'Alamofire'" happens because your framework doesn't actually include Alamofire when you use it in some other project, and you cannot import Alamofire in your sample project for the same reason.

If you plan to make your project a Pod you can include the following line in your podspec:

s.dependency "Alamofire", "~> 3.1.5" 

Including Alamofire as a dependency in the podspec instructs cocoapods to also include it when your framework is installed.

Hope it helps.

Answers 2

Not 100% sure if this is your issue of not, but for swift stuff you have to use the use_frameworks! directive in your Podfile. Could that be the issue?

I ran into this once and found answer from https://www.raywenderlich.com/97014/use-cocoapods-with-swift

Read More